import React from "react";
import { connect } from "react-redux";
import baseService from "share/base.service";
import moment from "moment";
import menuRoute from "routes/menuRoute";
import debounce from "lodash.debounce";
import {
  messages,
  mulCalculate,
  addCalculate,
  deepFullCopy,
  queryCurrencyPrecision,
  currencyPrecisionCal,
  subCalculate,
  omit,
  deepCopy,
  formatNumber,
} from "share/common";
import {
  Alert,
  Form,
  Switch,
  Icon,
  Input,
  Select,
  Button,
  Row,
  Col,
  message,
  Card,
  Popover,
  InputNumber,
  DatePicker,
  Spin,
  Tag,
  Table,
  Modal,
  Dropdown,
  Menu,
  Tooltip,
  notification,
} from "antd";
const confirm = Modal.confirm;
const { MonthPicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
import Chooser from "components/chooser";
import Location from "components/location";
import Invoice from "containers/my-account/invoice";
import ExpenseApportion from "containers/my-account/expense-apportion";
import "styles/my-account/new-expense.scss";
import ExpenseTypeSelector from "components/template/expense-type-selector";
import CreateInvoice from "containers/my-account/create-invoice";
import BusinessCardConsumption from "components/template/business-card-consumption-selector";
import DidiRecordSelector from "components/template/didi-record-selector";
import FileUpload from "components/file-upload";
import expenseService from "containers/my-account/expense.service";
import FileAudit from "containers/financial-management/finance-audit/file-audit";
import Selector from "components/selector";
import DateCombined from "containers/my-account/date-combined";
import config from "config";
import Searcher from "components/searcher";
import errorMessage from "share/errorMessage";
import chooserData from "share/chooserData";
import mileageSubsidyService from "containers/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.service";
import Condition from "components/condition";
const { If, Else } = Condition;
import IeFileUpload from "components/template/ie-file-upload/ie-file-upload";
import defaultExpenseTypeIcon from "images/expense/default-expense-type.png";
import ApproveHistory from "containers/my-account/components/approve-history";
import MileageAllowance from "containers/my-account/components/mileage-allowance";
import BusinessCard from "containers/my-account/components/business-card";
import DiDiCard from "containers/my-account/components/didi-card";
import InvoiceOCRCheck from "containers/my-account/components/invoice-ocr-check";
import InvoiceOCRList from "containers/my-account/components/invoice-ocr-list";
import dataSources from "containers/my-account/data-sources/data-sources";
import WayPointEdit from "../mileage-subsidy-expense/components/way-point-edit";
import WayPointMap from "containers/mileage-subsidy-expense/components/way-point-map";
import UnifiedTable from "components/template/widget/unified-table/UnifiedTable";
import SwitchWrapper from "components/template/widget/switch-wrapper/SwitchWrapper";
import TravelShare from "containers/my-account/components/travel-share";


const { unitInfo } = dataSources;

const DivExpense = (props) => {
  const childrenProps = { ...props };
  delete childrenProps.show;
  return <div className="new-expense" {...childrenProps} />;
};
let newExpenseThis;

/**
 * props.params
 * @params nowExpense 费用详细
 * @params expenseSource 费用来源  expenseType-手工录入 invoice-发票录入 card-商务卡消费
 * @params type 调用本组件的入口 0：我的账本 1：公务卡消费 2：滴滴 3：报销单
 * 页面上如果手动添加字段要考虑只读和可编辑两种情况
 */
class NewExpense extends React.Component {
  constructor(props) {
    super(props);
    newExpenseThis = this;
    let expenseReportInfo = props.expenseReport || {};
    this.state = {
      expenseLoading: false,
      businessCardConsumptions: [],
      didiRemark: "",
      didiArr: [],
      detailArr: [],
      singleBusinessCards: [], // 商务卡一对一模式选中的list
      expenseType: {}, //费用类型详情
      promptThan300: true,
      loading: false,
      saving: false,
      isNonVat: false,
      nowPage: "type", //type-费用类型选择、发票录入  card-商务卡消费选择页  form-费用表单页
      attachments: [],
      electronicAttachments: [], // 电子支付凭证的附件列表
      nowExpense: {},
      currencyList: [],
      nowCurrency: {
        rate: 1.0,
        currencyCode: props.company.baseCurrency,
      },
      baseCurrency: {
        currencyCode:
          expenseReportInfo.baseCurrency || props.company.baseCurrency,
      },
      typeSource: "", //expenseType invoice businessCard invoiceOCR
      expenseApportion: [],
      readOnly: false,
      receipt: {}, //发票对象实体
      receiptList: [], //发票对象数组
      receiptOperateScene: 1, //发票操作场景：1.发票创建费用；2.费用新增发票；3.费用编辑发票
      previewVisible: false,
      auditAmountEditing: false,
      savingAuditAmount: false,
      savingInvoice: false,
      showExpenseDom: false, //费用dom切换，控制开关
      defaultAttachment: null,
      approvalHistory: [],
      fromExpense: false,
      invoiceFp: null, //单据FP
      invoiceCompany: null, //单据的公司
      attachmentChange: false,
      warnExchangeRateTol: 10, //汇率容差警告值
      prohibitExchangeRateTol: 20, //汇率容差禁止值
      recommendExpenseTypeList: [] /*系统推荐的费用类型，根据发票信息查询的*/,
      unitPriceMode: false, //单价模式
      recordTaxRateConfig: false, //补录税率配置，当查验返回R_2002，需要强制显示税率／税额／不含税金额控件。切换发票类型取消。
      recordTaxAmountConfig: false, //补录税率配置，税额合计特殊处理
      recordNonVATinclusiveAmountConfig: false, //补录税率配置,金额合计特殊处理
      receiptConfigList: [], //发票控件配置对象信息
      mileageMessageKey: [
        "mileage",
        "unit.price",
        "reference.price",
        "reference.mileage",
        "reference.currency",
        "ER_KM",
        "mileage",
      ],
      subsidyData: [],
      pagination: {
        total: 0,
      },
      subsidyLoading: false,
      page: 0,
      columns: [
        {
          title: messages("common.date") /*日期*/,
          dataIndex: "subsidyDetailTime",
          width: "35%",
          render: (value) => (props.isWithTime ? value : value.substr(0, 10)),
        },
        {
          title: messages("common.amount") /*金额*/,
          dataIndex: "amount",
          width: "15%",
          render: (value, item) =>
            this.filterMoney(value, queryCurrencyPrecision(item.currencyCode)),
        },
        {
          title: messages("common.currency.rate") /*汇率*/,
          dataIndex: "currencyRate",
          width: "15%",
          render: (value) => this.filterMoney(value, 4),
        },
        {
          title: messages("common.base.currency.amount") /*本位币金额*/,
          dataIndex: "baseCurrencyAmount",
          width: "15%",
          render: (value) =>
            this.filterMoney(
              value,
              queryCurrencyPrecision(
                expenseReportInfo.baseCurrency || props.company.baseCurrency
              )
            ),
        },
        {
          title: messages("my-account.key179") /*补贴属性*/,
          dataIndex: "travelRule",
          width: "20%",
        },
      ],
      invoiceCurrencyCodePrecision: queryCurrencyPrecision(""), //费用币种精度
      actualApportionAmount: "", // 实际分摊金额
      ownerOID:
        (props.expenseReport || {}).applicantOID ||
        (props.applicant || {}).userOID ||
        props.agentOid ||
        (props.agentUser && props.agentUser.userOID) ||
        props.user.userOID, //费用归属人OID
      blurOriginalApprovedNonVat: null,
      weatherChangeOriginalApprovedNonVat: false,
      receiptIndex: 0, //发票index
      invoiceList: [], // 费用列表
      showOCRFlag: false, //是否开通OCR
      OCRList: [], //OCR查验列表
      businessCardType: "", // 商务卡规则是一对多 或者是多对一
      isBusinessCardMore: false, // 商务卡模式是否支持一对多和一对一
      showFileAudit: false,
      isWorthAmount: false, // 对金额输入实时展示分摊防抖
      showExpenseReportInvoices: props.showExpenseReportInvoices,
      visible: false,
      carNum: "",
      allSelectedRecords: [], // 公务卡消费明细数组
      isShowPlayerList: true,
      filterExpenseTypesArr: [], // 要被剔除掉的费用类型（由不同的入口决定）（注：当滴滴进入的时候，接口返回的不是剔除的，是要显示的九种）
      nowDate: moment().format("YYYY-MM-DD"),
      didiModalInfo: "", // 滴滴打车消费生成费用过程中的提示信息
      showDiDiModal: false, // 在滴滴生成费用过程中是否展示提示弹窗
      startDate: undefined,
      endDate: undefined,
      lastExpenseDetail: {},
      isThan5000: true,
      isDiDiChange: false,
      feeAcknowledgers: [], // 洗衣费 共享人列表
      unitPrice: 0,
      businessCardEnabledObj: {
        companyEnable: false, // 根据接口获取的关于费用申请人所在公司和招行是否有关
        remainData: false, // 根据接口获取的申请人是否有剩余的公务卡消费数据
      },
      feeAcknowledgersIsSwitch: false,
      need5000: false,
      dontNeed5000: false,
      officeCardShow: false,
      isRelationDidi: false,
      didiOrderId: "",
      didiRelationAmount: "",
      notShowFileList: [], // 不展示电子支付凭证附件的类型
      amountValue: 0, // 填写的金额


    };

    this.handleToTalMoneyChange = debounce(this.handleToTalMoneyChange, 300);
    this.getInvoiceTaxAmount = debounce(this.getInvoiceTaxAmount, 300);
  }

  dateCombinedRef = null

  componentDidMount() {
    window.tt123 = this
    window.moment = moment
    if (window.addEventListener) {
      window.addEventListener("keyup", this.handleKeyUp);
    } else {
      window.attachEvent("onkeyup", this.handleKeyUp);
    }
    let companyOID = undefined;
    if (this.props.expenseReport) {
      let companyData = this.props.expenseReport.custFormValues.filter((e) => {
        return e.fieldName === "费用承担公司";
      });
      companyOID = companyData[0].value;
    } else {
      companyOID = this.props.company.companyOID;
    }
    baseService.getQueryPrice(companyOID).then((res) => {
      console.log("res", res);
      if (res.data && res.data.rows) {
        this.setState({ unitPrice: res.data.rows.unitPrice });
      }
    });
    let customEnumerationOID = '89241651-0fa3-418e-859a-aea997f614b6'
    // 注意！！！
    // 正式环境和测试环境的id不一样 所以在prod分支改成下面的，后续从prod切分支出来合dev这里应该会有冲突，注意不要搞错
    // let customEnumerationOID = '9b9b3f50-0fa1-4ea3-bfd5-e45942aa4fce'
    expenseService.getNotShowFileList(customEnumerationOID).then((res) => {
      if (res.data && res.data.length) {
        let arr = [];
        res.data.forEach(item=>{
          arr.push(item.code);
        })
        this.setState({ notShowFileList: arr });
      }
    });
    // setTimeout(() => {
      this.setTreeFieldShow();
    // }, 1000);
  }

  componentDidUpdate(prevProps, prevState) {
    // 参数分别为改变之前的数据状态对象
    // 无法提供
    if (prevState.businessCardConsumptions.length != this.state.businessCardConsumptions.length) {
      console.log(123456);
      this.setTreeFieldShow()
    }
  }
  // 根据公务卡长度 判断可提供电子金额、无法提供电子金额、无法提供申请单三个字段是否显示
  setTreeFieldShow = () => {
    let lengthFlag = this.state.businessCardConsumptions.length === 0
    const { expenseType, nowExpense } = this.state;
    console.log('hhhexpenseType', expenseType, nowExpense);
    console.log('lengthFlag', lengthFlag);
    if(nowExpense.data){
      nowExpense.data.forEach(item => {
        // 'dianzizhif', 
        if (['dianzizhif', 'wudianzizhif'].includes(item.messageKey)) {
          console.log('yesyes');
          item.value = '0';
          item.showOnList = lengthFlag;
        }
        if (item.name === '无法提供电子支付凭证申请单') {
          item.value = null;
          item.showOnList = lengthFlag;
        }
      })
      this.setState({ nowExpense, electronicAttachments: [] })
      return;
    }
    if(expenseType.fields){
      expenseType.fields.forEach(item => {
        // 'dianzizhif', 
        if (['dianzizhif', 'wudianzizhif'].includes(item.messageKey)) {
          console.log('yesyes');
          item.value = '0';
          item.showOnList = lengthFlag;
        }
        if (item.name === '无法提供电子支付凭证申请单') {
          item.value = null;
          item.showOnList = lengthFlag;
        }
      })
      this.setState({ expenseType, electronicAttachments: [] })
      return;
    }
    
  }

  componentWillUnmount() {
    if (window.addEventListener) {
      window.removeEventListener("keyup", this.handleKeyUp);
    } else {
      window.detachEvent("onkeyup", this.handleKeyUp);
    }
  }

  // 获取不同入口要剔除或展示的费用类型，只有type===2的时候接口返回的是要展示的费用类型，其他都是要剔除的
  getFilterExpenseTypes = async (type) => {
    const res = await expenseService.getFilterExpenseTypes(type);
    if (res.status === 200) {
      if (res.data && res.data.length > 0) {
        this.setState({
          filterExpenseTypesArr: res.data,
        });
      }
    }
  };

  onCancel = (refresh = false) => {
    this.setState({
      isDiDiChange: false,
      didiArr:[],
    });
    this.props.form.resetFields();
    refresh = this.state.attachmentChange ? true : refresh;
    console.log(this.props,'777777777222');
    if (this.props.params.type === 3) {
      this.props.params.onClose()
    } else if(this.props.params.didiId === 1){
    this.props.params.closeShow()
    } else {
    this.props.closeFun();
    }
    // if (this.props.officialCard) {
    //   this.props.closeFun();
    // } else {
    //   this.props.close(refresh);
    // }
  };

  //根据用户OID获取FP，用户不同用户操作同一页面。如财务操作用户费用页面，取员工FP
  getFpByUserOID(userOID) {
    let { invoiceFp, invoiceCompany } = this.state;
    baseService.getFpByUserOID(userOID).then((res) => {
      invoiceFp = res.data;
      this.setState({ invoiceFp });
    });
    baseService.getCompanyByUserOID(userOID).then((res) => {
      invoiceCompany = res.data;
      this.setState({ invoiceCompany });
    });
  }

  getCurrencyFromList = (currencyCode) => {
    let result = {};
    this.state.currencyList.map((item) => {
      if (item.currency === currencyCode) {
        item.currencyCode = item.currency;
        result = item;
      }
    });
    return result;
  };

  /**
   * 校验是否展示关联公务卡按钮
   * 1、该费用已经关联了公务卡
   * 2、费用申请人所在公司和招商银行有关系且有公务卡消费记录
   * 以上两条一条满足即可
   */
  validateBusinessCardEnabled() {
    const { user, agentOid, agentUser } = this.props;
    let userOID = agentOid || (agentUser ? agentUser.userOID : user.userOID);
    if (this.props.applicant && this.props.applicant.userOID) {
      userOID = this.props.applicant.userOID;
    }
    Promise.all([
      /**
       * baseService.getBusinessCardConsumptionList这个接口的page size传0，0时
       * 意味着不是真的想获取公务卡数据，只是想判断这个用户是否有公务卡消费记录
       * 因为获取公务卡消费记录的时候会剔除掉已关联的公务卡消费记录
       * 如果用户的所有公务卡消费记录都被关联了，就查不出来数据了，所以增加了这一条传参约定
       */
      baseService.getBusinessCardConsumptionList("CMBC", false, userOID, 0, 0),
      expenseService.getBusinessCardStatus(userOID),
    ]).then((res) => {
      this.setState({
        businessCardEnabledObj: {
          companyEnable: res[1].data.rows,
          remainData: res[0].data.success && res[0].data.rows.length > 0,
        },
      });
    });
  }

  componentWillMount() {
    const { user, agentOid, agentUser } = this.props;
    let userOID = agentOid || (agentUser ? agentUser.userOID : user.userOID);
    if (
      this.props.params &&
      this.props.params.audit &&
      this.props.params.expenseReport
    ) {
      userOID = this.props.params.expenseReport.applicantOID;
      userOID && this.getFpByUserOID(userOID);
    }
  }

  componentWillReceiveProps(nextProps) {
    console.log("nextProps", nextProps)
    let switchingInvoiceConfig =
      nextProps.nowExpense &&
      this.props.nowExpense &&
      nextProps.nowExpense.invoiceOID !== this.props.nowExpense.invoiceOID;
    if (
      nextProps.slideFrameShowFlag === this.props.slideFrameShowFlag &&
      !switchingInvoiceConfig
    ) {
      return;
    } else if (nextProps.slideFrameShowFlag === false) {
      this.setState({
        nowPage: nextProps.expenseSource === "businessCard" ? "card" : "type",
        typeSource: "",
        nowExpense: {},
        recordTaxRateConfig: false,
        recordTaxAmountConfig: false,
        recordNonVATinclusiveAmountConfig: false,
        attachments: [],
        electronicAttachments: [],
        businessCardConsumptions: [],
        expenseType: {},
        invoiceCurrencyCodePrecision: queryCurrencyPrecision(""),
        receiptList: [],
        receipt: {},
        auditAmountEditing: false,
        readOnly: false,
        weatherChangeOriginalApprovedNonVat: false,
        saving: false,
        allSelectedRecords: [],
        isDiDiChange: false,
        isRelationDidi: false,
        didiRelationAmount:'',
        didiOrderId:''
      });
      nextProps.form.resetFields();
      return;
    }
    // 调用本组件的入口 0：我的账本 1：公务卡消费 2：滴滴 3：报销单
    if (
      nextProps.didiExpenseInfo &&
      [0, 1, 2, 3].includes(this.props.params.type)
    ) {
      this.getFilterExpenseTypes(2);
    } else {
      this.getFilterExpenseTypes(this.props.params.type);
    }
    this.validateBusinessCardEnabled();
    this.getCurrencyList();
    this.getRateDeviation();
    this.getMileageMode();
    this.setState({
      receiptOperateScene: nextProps.params.receiptOperateScene,
      actualApportionAmount: "",
      allSelectedRecords: deepFullCopy(nextProps.allSelectedRecords || []),
    });

    //转交的费用，取费用归属人的FP
    let ownerOID =
      (nextProps.params.nowExpense && nextProps.params.nowExpense.ownerOID) ||
      (nextProps.params.owner && nextProps.params.owner.userOID) ||
      nextProps.params.agentOid ||
      (nextProps.params.user && nextProps.params.user.userOID) ||
      (this.props.expenseReport || {}).applicantOID ||
      this.props.userOID;
    this.setState({ ownerOID });
    const propsOwnerOID =
      (this.props.expenseReport || {}).applicantOID ||
      this.props.agentOid ||
      this.props.user.userOID;
    if (!nextProps.params.audit && ownerOID !== propsOwnerOID) {
      this.getFpByUserOID(ownerOID);
    }
    nextProps.form.resetFields();
    this.getOCRFlag(ownerOID, nextProps.expenseSource);
    //更换费用录入类型时，重置界面到type
    if (
      nextProps.expenseSource !== this.state.typeSource &&
      !nextProps.nowExpense
    ) {
      this.setState({
        typeSource: nextProps.expenseSource,
        nowPage: nextProps.expenseSource === "businessCard" ? "card" : "type",
        businessCardConsumptions: [],
      });
    }
    let businessCode = undefined;
    try {
      businessCode = nextProps.params.expenseReport.businessCode;
    } catch (e) {
      if (config.appEnv === "dev")
        console.log("bussinessCode未获取, 当前参数：", nextProps.params);
    }
    console.log(this.state.didiArr,'==========');
    if (nextProps.nowExpense && this.state.didiArr.length === 0) {
      const _this=this
      baseService
        .getDIDIOid(nextProps.nowExpense.invoiceOID, {
          businessCode,
        }).then((res) => {
          let didiArr = [];
          let expenseDetail = res.data;
          didiArr = expenseDetail.map(
            (record, index) => {
              if (!record.relationMap) {
                record.relationMap = {};
              }
              if (
                record.relationMap.INVOICE &&
                record.relationMap.INVOICE.length > 0
              ) {
                const INVOICE = record.relationMap.INVOICE.map((relation) => {
                  if (relation.atlBankTransactionId === expenseDetail.id) {
                    relation.checked = true;
                  }
                  return relation;
                });
                record.relationMap.INVOICE = INVOICE;
              }
              return record;
            }
          );
          console.log(didiArr,'didiArr');
          this.setState({ didiArr })
        })
    }

    //费用改变时
    if (
      nextProps.nowExpense &&
      (!this.state.nowExpense ||
        this.state.nowExpense.invoiceOID !== nextProps.nowExpense.invoiceOID)
    ) {
      this.setState({ nowPage: "", typeSource: "", expenseLoading: true });
      // console.log('+++++++++++++++++++++++++++++——————————————————');
      baseService
        .getInvoiceDetail(nextProps.nowExpense.invoiceOID, {
          businessCode,
        })
        .then((res) => {
          console.log("res.data", res);
          let expenseDetail = res.data;
          console.log('expenseDetail', expenseDetail);
          this.setState({ detailArr: expenseDetail, amountValue: res.data.amount })
          
          baseService
          .getDIDIOid(expenseDetail.invoiceOID,{
            businessCode,
          }).then((res) => {
            let didiArr = res.data;
            this.setState({didiArr})
          })
          let isNonVat = res.data.vatInvoice;
          if (nextProps.isCopy) {
            expenseDetail = this.initCopyData(expenseDetail);
          }
          expenseDetail.data &&
            expenseDetail.data.sort((a, b) => a.sequence > b.sequence || -1);
          expenseDetail.preCreatedDate = expenseDetail.createdDate;
          let businessCardConsumptions = [];
          if (expenseDetail.atlBankTransactions) {
            expenseDetail.atlBankTransactions.map(
              (selectedRecord, selectedRecordIndex) => {
                const keys = Object.keys(selectedRecord.relationMap);
                if (!selectedRecord.relationMap) {
                  selectedRecord.relationMap = {};
                }
                if (!selectedRecord.relationMap.WAIT) {
                  selectedRecord.relationMap.WAIT = [];
                }
                selectedRecord.relationMap.WAIT.push({
                  amount: selectedRecord.remainAmt || 0,
                  atlBankTransactionId: selectedRecord.id,
                  checked: false,
                });

                keys.map((key, keyIndex) => {
                  if (!selectedRecord.relationMap[key]) {
                    selectedRecord.relationMap[key] = [];
                  }
                  if (key === "INVOICE") {
                    selectedRecord.relationMap[key].map(
                      (selectedRelation, selectedRelationIndex) => {
                        selectedRelation.checked = false;
                        if (
                          selectedRelation.artInvoiceOid ===
                            expenseDetail.invoiceOID &&
                          selectedRelation.amount !== 0
                        ) {
                          selectedRelation.checked = true;
                        }
                      }
                    );
                  } else {
                    selectedRecord.relationMap[key].map((relation) => {
                      relation.checked = false;
                    });
                  }
                  const checkRes = this.validateAllChecked(selectedRecord);
                  switch (checkRes) {
                    case 0:
                    case 1:
                    case 3:
                      selectedRecord.checked = false;
                      break;
                    case 2:
                      selectedRecord.checked = true;
                      break;
                    default:
                      break;
                  }
                });
              }
            );
            expenseDetail.atlBankTransactions =
              expenseDetail.atlBankTransactions || [];
            businessCardConsumptions = expenseDetail.atlBankTransactions.map(
              (record, index) => {
                if (!record.relationMap) {
                  record.relationMap = {};
                }
                if (
                  record.relationMap.INVOICE &&
                  record.relationMap.INVOICE.length > 0
                ) {
                  const INVOICE = record.relationMap.INVOICE.map((relation) => {
                    if (relation.atlBankTransactionId === expenseDetail.id) {
                      relation.checked = true;
                    }
                    return relation;
                  });
                  record.relationMap.INVOICE = INVOICE;
                }
                return record;
              }
            );
          }
          if (
            expenseDetail.receiptList &&
            expenseDetail.receiptList.length > 0
          ) {
            let taxCodeList = [],
              receipts = [],
              configResults = [];
            expenseDetail.receiptList.map((item) => {
              item.invoiceGoods &&
                item.invoiceGoods.map((i) => {
                  i.taxCode && taxCodeList.push(i.taxCode);
                });
              if (item.configResultDTO) {
                configResults.push(item.configResultDTO);
              }
              receipts.push({
                receiptTypeNo: item.invoiceTypeNo,
                taxCodes: taxCodeList,
              });
            });
            receipts.length > 0
              ? this.getRecommendExpenseTypeList(receipts, configResults)
              : this.setState({ recommendExpenseTypeList: [] });
          } else {
            this.setState({ recommendExpenseTypeList: [] });
          }
          let nowCurrency = this.getCurrencyFromList(
            expenseDetail.currencyCode
          );
          if (
            this.state.baseCurrency.currencyCode !== nowCurrency.currencyCode
          ) {
            nowCurrency.rate = expenseDetail.companyCurrencyRate;
          }
          //设置可分摊金额
          let invoiceUserFp = this.state.invoiceFp
            ? this.state.invoiceFp
            : nextProps.profile;
          if (
            invoiceUserFp["all.total.amount.apportionment"] === false &&
            expenseDetail.amount !== expenseDetail.expenseAmount
          ) {
            this.setState({
              actualApportionAmount: expenseDetail.expenseAmount,
            });
          }
          if (expenseDetail.expenseTypeCode === "MCD1047") {
            expenseDetail.data.map((item) => {
              if (item.messageKey === "mcd.car") {
                item.value = JSON.parse(JSON.stringify(item.value));
              }
            });
          }
          let startDate = undefined;
          let endDate = undefined;
          expenseDetail.data.map((item) => {
            if (item.messageKey === "total.amount" && item.value) {
              this.setState({ didiRelationAmount: item.value });
            }
          });
          //使用滴滴订单id是否有值作为 是否关联滴滴的标识
          if (expenseDetail.didiOrderIds && expenseDetail.didiOrderIds.length > 0) {
            this.setState({
              isRelationDidi: true,
              didiOrderId: expenseDetail.orderId,
            });
          } else {
            this.setState({ isRelationDidi: false });
          }
          this.setState({
            readOnly: nextProps.readOnly,
            nowPage: "form",
            typeSource: "",
            nowCurrency: nowCurrency,
            nowExpense: expenseDetail,
            receiptList: expenseDetail.receiptList,
            invoiceCurrencyCodePrecision: queryCurrencyPrecision(
              expenseDetail.invoiceCurrencyCode
            ),
            approvalHistory: expenseDetail.approvalOperates,
            attachments: expenseDetail.attachments,
            electronicAttachments: expenseDetail.electronicAttachments || [],
            businessCardConsumptions,
            expenseApportion: expenseDetail.expenseApportion,
            isNonVat: isNonVat,
            page: 0,
            taxRate: expenseDetail.taxRate,
            invoiceList: deepFullCopy(nextProps.expenseReportInvoices || []),
            showExpenseReportInvoices: deepFullCopy(
              nextProps.showExpenseReportInvoices || []
            ),
            isWorthAmount: expenseDetail.amount !== 0,
            feeAcknowledgers: expenseDetail.feeAcknowledgers,
            officeCardShow:
              expenseDetail.atlBankTransactions &&
              expenseDetail.atlBankTransactions.length > 0
                ? true
                : false,
            startDate,
            endDate,
          });
          let subsidyParams = {
            invoiceOID: nextProps.nowExpense.invoiceOID,
            page: 0,
            size: 10,
          };
          this.setState({ subsidyLoading: true });
          Promise.all([
            baseService.getExpenseTypeById(nextProps.nowExpense.expenseTypeId),
            nextProps.nowExpense.expenseTypeSubsidyType &&
              expenseService.getSubsidy(subsidyParams),
          ])
            .then((res) => {
              this.setState({ expenseLoading: false });
              //里程补贴的readonly是true，但是他是可以编辑的
              const { page } = this.state;
              let readOnly =
                nextProps.readOnly ||
                (res[0].data.readonly &&
                  res[0].data.messageKey !== "private.car.for.public");
              if (
                res[0].data.messageKey === "private.car.for.public" &&
                this.state.unitPriceMode
              ) {
                mileageSubsidyService.queryDeviateValue().then((res) => {
                  if (res.data) {
                    const { unitPriceRange, editable } = res.data;
                    this.setState({ unitPriceRange, lovEditable: editable });
                  }
                });
              } else {
                this.setState({ unitPriceRange: 0, lovEditable: true });
              }
              if (res[1]) {
                this.setState({
                  subsidyData: res[1] ? res[1].data : [],
                  pagination: {
                    total: Number(res[1].headers["x-total-count"]),
                    onChange: this.onChangePager,
                    current: page + 1,
                  },
                  subsidyLoading: false,
                });
              }
              console.log("expenseDetail", expenseDetail);
              this.setState(
                {
                  expenseType: res[0].data,
                  expenseTypeCache: deepCopy(res[0].data),
                  lastExpenseDetail: res[0].data,
                  isThan5000: expenseDetail.amount > 5000 ? false : true,
                  readOnly,
                  nowDate: expenseDetail.createdDate,
                },
                () => {
                  const { expenseType } = this.state;
                  this.updateShowAssiciateApplication();
                  this.getFieldEnumerationList();
                  expenseDetail.amount = Number(
                    currencyPrecisionCal(
                      expenseDetail.invoiceCurrencyCode,
                      expenseDetail.amount
                    )
                  );
                  let value = {
                    createdDate: moment(expenseDetail.createdDate),
                    invoiceCurrencyCode: expenseDetail.invoiceCurrencyCode,
                    amount: expenseDetail.amount,
                    actualCurrencyRate: expenseDetail.actualCurrencyRate,
                    payByCompany: expenseDetail.paymentType === 1002,
                    comment: expenseDetail.comment || "",
                  };
                  if (expenseDetail.bankTransactionID) {
                    value.businessCardRemark =
                      expenseDetail.bankTransactionDetail.remark;
                  }
                  if (expenseDetail.applicationNumber) {
                    value.applicationNumber = [
                      {
                        businessCode: expenseDetail.applicationNumber,
                      },
                    ];
                    //第三方费用类型渲染有点问题
                    setTimeout(() => {
                      nextProps.form.setFieldsValue({
                        applicationNumber: value.applicationNumber,
                      });
                    }, 50);
                  }
                  if (!this.props.profile["invoice.instead.disabled"])
                    value.invoiceInstead = expenseDetail.invoiceInstead;
                  //替票理由，如果不提票则不set对应值
                  if (expenseDetail.invoiceInstead)
                    value.invoiceInsteadReason =
                      expenseDetail.invoiceInsteadReason || "";
                  //遍历费用表单，将OID设置为表单id
                  expenseDetail.data.map((field, index) => {
                    if (
                      field.showOnList &&
                      !(
                        expenseDetail.paymentType === 1001 &&
                        field.messageKey === "company.payment.type"
                      )
                    ) {
                      value[field.fieldOID] = this.getFieldDefaultValue(
                        field.fieldType,
                        field.value,
                        field.showValue,
                        field
                      );
                    }
                  });
                  !readOnly && nextProps.form.setFieldsValue(value);
                  //第三方费用只set发票相关
                  if (
                    !nextProps.readOnly &&
                    res[0].data.readonly &&
                    res[0].data.messageKey !== "private.car.for.public"
                  ) {
                    let valueWillSet = {};
                    if (!this.props.profile["invoice.instead.disabled"])
                      valueWillSet.invoiceInstead =
                        expenseDetail.invoiceInstead;
                    if (expenseDetail.invoiceInstead)
                      valueWillSet.invoiceInsteadReason =
                        expenseDetail.invoiceInsteadReason || "";
                    nextProps.form.setFieldsValue(valueWillSet);
                  }
                  if (
                    expenseType &&
                    expenseType.name &&
                    expenseType.name.indexOf("滴滴") !== -1
                  ) {
                    this.setState({ isDiDiChange: true });
                  }
                }
              );

              // if (this.chooser) {
              //   const item = this.state.detailArr.data.find(i=> i.messageKey === "associate.application")
              //   let associate = item.value
              //   console.log(associate, item, '_____');
              //   console.log('单据测试');
              //   this.chooser.handleListOk({result: [{...item, businessCode: item.value}]}, 'handleListOk')
              // }

              if(this.dateCombinedRef) {
                // console.log(this.state.detailArr)

                if(this.state.detailArr.data) {
                  const dateCombined = this.state.detailArr.data.find(i=> i.messageKey === 'dateCombined')
                  if(dateCombined && dateCombined.value) {
                    let {startDate, endDate} = JSON.parse(dateCombined.value)
                    startDate = moment(startDate)
                    endDate = moment(endDate)
                    console.log(startDate, endDate)

                    this.dateCombinedRef.onChangeDate([startDate, endDate])

                    // this.props.form.setFieldsValue({[dateCombined.fieldOID]: `{"startDate":"2023-06-07T16:00:00Z","endDate":"2023-07-04T16:00:00Z","duration":28}`})
                  }
                }

              }
            })
            .catch((e) => {
              console.log('eee', e)
              this.setState({ expenseLoading: false });
            });
        })
        .catch((e) => {
          console.log('eeeee',e)
          errorMessage(e.response);
          this.setState({ expenseLoading: false });
        });
    } else if (!nextProps.nowExpense) {
      //如果为新建，重置数据
      let earliestDate = null;
      if (this.props.officialCard) {
        let createDateArr = deepFullCopy(nextProps.allSelectedRecords || [])
          .filter(
            (item) =>
              item.selectedRelationList && item.selectedRelationList.length > 0
          )
          .map((item) => moment(item.trsDate || "").valueOf());
        earliestDate = moment(Math.min(...createDateArr)).format("YYYY-MM-DD");
      }

      this.setState({
        nowPage: nextProps.expenseSource === "businessCard" ? "card" : "type",
        nowExpense: { owner: nextProps.owner || {} },
        attachments: [],
        electronicAttachments: [],
        expenseDetail:{},
        invoiceCurrencyCodePrecision: queryCurrencyPrecision(""),
        expenseApportion: [],
        recommendExpenseTypeList: [],
        isBusinessCardMore: true,
        feeAcknowledgers: [],
        nowDate: earliestDate ? earliestDate : this.state.nowDate,
        amountValue: 0,
      });
      let currencyCode = nextProps.expenseReport
        ? nextProps.expenseReport.currencyCode
        : this.props.company.baseCurrency;
      this.props.form.setFieldsValue({ invoiceCurrencyCode: currencyCode });
      this.getCurrencyList(true, currencyCode);
    }
  }

  /**
   * 检查这条公务卡数据中可选的公务卡消费明细是否全选
   * @param {Object} record 一条完整的公务卡数据
   * return 0 // 待拆分、已拆分、已关联公务卡明细数量为0
   * return 1 // 已勾选数量为0
   * return 2 // 待拆分、已拆分、已关联公务卡明细被全选
   * return 3 // 部分勾选
   */
  validateAllChecked = (record) => {
    const relationMap = record.relationMap || {};
    const keys = Object.keys(relationMap);
    let total = 0;
    let checked = 0;
    keys.map((key) => {
      // 判断这个公务卡的公务卡明细是否被全选
      if (key === "INVOICE") {
        relationMap[key].map((relation) => {
          if (relation.artInvoiceOid === this.props.invoiceOID) {
            total++;
            if (relation.checked) {
              checked++;
            }
          }
        });
      } else if (["WAIT", "NONE"].includes(key)) {
        relationMap[key].map((relation) => {
          if (relation.amount !== 0) {
            total++;
            if (relation.checked) {
              checked++;
            }
          }
        });
      }
    });
    if (total === 0) {
      return 0; // 待拆分、已拆分、已关联公务卡明细数量为0
    }
    if (checked === 0) {
      return 1; // 已勾选数量为0
    }
    if (total === checked) {
      // 全选
      return 2; // 待拆分、已拆分、已关联公务卡明细被全选
    }
    return 3; // 部分勾选
  };

  //获取币种列表
  getCurrencyList = (isRenderCurrency, currencyCode) => {
    let { currencyList } = this.state;
    if (currencyList[0]) {
      isRenderCurrency && this.handleChangeCurrency(currencyCode);
      return;
    }
    let userOID =
      (this.props.expenseReport || {}).applicantOID ||
      this.props.agentOid ||
      this.props.user.userOID;
    const { audit, expenseReport } = this.props.params || {};
    if (audit && expenseReport) {
      userOID = expenseReport.applicantOID;
      userOID && this.getFpByUserOID(userOID);
    }
    let jobId = expenseReport ? expenseReport.applicantJobId : undefined;
    baseService
      .getAllCurrencyByLanguage("zh_cn", userOID, true, false, jobId)
      .then((res) => {
        this.setState({ currencyList: res.data || [] }, () => {
          isRenderCurrency && this.handleChangeCurrency(currencyCode);
        });
      });
  };

  //获取是否为单价模式
  getMileageMode = () => {
    expenseService.getMileageMode().then((res) => {
      this.setState({ unitPriceMode: res.data.mode === 9001 });
    });
  };

  //根据发票获取费用默认值（每次修改发票或者费用类型时都需要查询）
  getDefaultValueByInvoice = () => {
    const { getFieldValue, setFieldsValue } = this.props.form;
    const { expenseType, receiptList } = this.state;
    if (expenseType.expenseTypeOID && receiptList && receiptList.length) {
      expenseService
        .getDefaultValueByInvoice(expenseType.id, receiptList)
        .then((res) => {
          res.data &&
            res.data.map((item) => {
              let value = this.getFieldDefaultValue(
                item.fieldType,
                item.value,
                item.showValue
              );
              //当前字段没有值时才会将默认值填进去
              if (
                !getFieldValue(item.fieldOID) ||
                !String(getFieldValue(item.fieldOID))
              ) {
                setFieldsValue({ [item.fieldOID]: value });
              }
            });
        });
    }
  };

  //获取是否开通OCR
  getOCRFlag = (userOID, typeSource) => {
    //发票查验时，create-invoice页面也会请求该接口
    typeSource !== "invoice" &&
      expenseService.getTitleList(userOID).then((res) => {
        this.setState({ showOCRFlag: res.data.showOCRFlag });
      });
  };

  /**
   * 复制费用数据初始化处理
   * @param expenseDetail
   */
  initCopyData = (expenseDetail) => {
    let copyInvoice = deepFullCopy(expenseDetail);
    delete copyInvoice.invoiceOID;
    copyInvoice.attachments = [];
    copyInvoice.electronicAttachments = [];
    copyInvoice.receiptList = [];
    copyInvoice.invoiceLabels = [];
    // 商务卡信息
    delete copyInvoice.bankTransactionDetail;
    delete copyInvoice.bankTransactionID;
    delete copyInvoice.overDue;
    // 费用归属人处理
    copyInvoice.sourceOwner = JSON.parse(JSON.stringify(copyInvoice.owner));
    delete copyInvoice.owner;
    // 关联申请单需要处理
    const applicationField = copyInvoice.data.filter((item) => {
      return item.fieldType === "ASSOCIATE_APPLICATION";
    })[0];
    applicationField && (applicationField.value = "");
    // 分摊处理
    if (copyInvoice.expenseApportion) {
      let amount = copyInvoice.amount;
      copyInvoice.expenseApportion.forEach((item) => {
        delete item.id;
        item.amount = Number((amount * item.proportion).toFixed(2));
        if (item.amount < 0) {
          item.amount = -item.amount;
        }
      });
    }
    return copyInvoice;
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState(
        {
          page: page - 1,
        },
        () => {
          const { page } = this.state;
          let subsidyParams = {
            invoiceOID: this.props.nowExpense.invoiceOID,
            page: page,
            size: 10,
          };
          this.setState({ subsidyLoading: true });
          expenseService
            .getSubsidy(subsidyParams)
            .then((res) => {
              this.setState({
                subsidyData: res.data,
                pagination: {
                  total: Number(res.headers["x-total-count"]),
                  onChange: this.onChangePager,
                  current: page + 1,
                },
                subsidyLoading: false,
              });
            })
            .catch(() => {
              message.error(messages("my-account.key71" /*系统异常*/));
            });
        }
      );
  };

  isRequiredFile = () => {
    //attachmentRequired用于配置附件是否必填，0为不必填，1为始终必填，
    // 2为有发票时不必填 : 费用中有导入、扫入、录入发票或费用为无票时，附件不必填，
    // 3有发票电子原件不必填
    const { receiptList, expenseType } = this.state;
    const amount = this.props.form.getFieldValue('amount');

    if (["MCD1094", "MCD1147"].includes(expenseType.code) && Number(amount) > 300) {
      return true;
    }
    if (["MCD1094"].includes(expenseType.code) && Number(amount) <= 300) {
      return false;
    }
    // https://pmo.mcd.com.cn/jira/browse/TES-2402
    if (expenseType.code === "MCD1236") {
      return false;
    }

    if (expenseType.attachmentRequired === 1) {
      return true;
    }
    if (
      expenseType.attachmentRequired === 2 &&
      expenseType.pasteInvoiceNeeded &&
      receiptList.length === 0
    ) {
      return true;
    }
    // 代第三方报销附件必填
    // if (this.props.expenseReport && this.props.expenseReport.formCode && this.props.expenseReport.formCode === 'BX006') {
    //   return true;
    // }
    let allHasPdfUrl = true;
    if (receiptList && receiptList.length > 0) {
      receiptList.map((item) => {
        if (item.pdfUrl && !item.pdfDamaged) {
          allHasPdfUrl = allHasPdfUrl ? true : false;
        } else {
          allHasPdfUrl = false;
        }
      });
    } else {
      allHasPdfUrl = false;
    }
    if (expenseType.attachmentRequired === 3 && !allHasPdfUrl) {
      return true;
    }
    return false;
  };

  isRequiredNewFile = (expenseType) => {
    // - [ ] 账本 /my-account/my-account-management
    // - [ ] 报销单 /expense-parent-report/expense-report

    const {pathname} = window.location;
    const {businessCardConsumptions} = this.state;
    const { params } = this.props;
    const { expenseReport } = params;
    console.log('info12345', this.props);
    let flagMoney = expenseType.fields && expenseType.fields.some(item=>item.messageKey === 'dianzizhif' && Number(this.props.form.getFieldValue(item.fieldOID)) === 0)
    // console.log('flagMoney', flagMoney);
    if(pathname.includes('my-account-management')){
      // 如果是账本
      console.log('当前是账本');
      // checkedNum的计算逻辑是复制下面的，原有的逻辑
      let checkedNum = 0;
      let recordOriAmount = 0;
      let oriCurCod = "";
      if(businessCardConsumptions.length){
        const businessCardTotalAmount = businessCardConsumptions.reduce(
          (pre, now) => {
            if (!now.relationMap) {
              now.relationMap = {};
            }
            const keys = Object.keys(now.relationMap);
            const recordAmount = keys.reduce((preKeyAmount, key) => {
              let keyAmount = 0;
              if (now.relationMap[key] && now.relationMap[key].length > 0) {
                keyAmount = now.relationMap[key].reduce((total, relation) => {
                  if (relation.amount !== 0 && relation.checked) {
                    checkedNum++;
                    if (!oriCurCod || oriCurCod.length === 0) {
                      oriCurCod = relation.oriCod;
                    }
                    recordOriAmount = recordOriAmount + relation.oriAmount;
                    return relation.amount + total;
                  }
                  return 0 + total;
                }, 0);
              }
              return preKeyAmount + keyAmount;
            }, 0);
            return pre + recordAmount;
          },
          0
        );
      }
      
      // 账本：如关联公务卡，无需必填，费用保存时校验，强管控
      if(checkedNum !== 0){
        return false;
      }else{
        return !flagMoney;
      }

    }
    if(pathname.includes('expense-parent-report')){
      // 如果是报销单
      console.log('当前是报销单');
      if(['BX001', 'BX003', 'BX006'].includes(expenseReport.formCode)){
        return !flagMoney;
      }
      if(['BX005'].includes(expenseReport.formCode)){
        if(checkedNum !== 0){
          return false;
        }else{
          return !flagMoney;
        }
      }
      if(['BX002', 'BX004'].includes(expenseReport.formCode)){
        return false;
      }
    }

  }

  isRequiredApply = (expenseType) => {
    const {amountValue} = this.state;
    console.log('info12345', this.props);
    let flagLessMoney = expenseType.fields && expenseType.fields.some(item=>item.messageKey === 'dianzizhif' && Number(this.props.form.getFieldValue(item.fieldOID)) < amountValue)
    console.log('flagLessMoney', flagLessMoney);
    return flagLessMoney
  }

  handleChangeAmount = (value, field) => {
    // console.log('value>>>>>>>>', value, field);
    this.setState({amountValue: value});
    // 金额发生变化时变更电子支付金额
    if(field && field.length){
      field.forEach(item=>{
        if(item.messageKey === 'dianzizhif'){
          let name = item.fieldOID;
          let obj ={};
          obj[name] = value;
          this.props.form.setFieldsValue(obj)
        }
        if(item.messageKey === 'wudianzizhif'){
          let name = item.fieldOID;
          item.value = 0;
          let obj ={};
          obj[name] = 0;
          this.props.form.setFieldsValue(obj)
        }
      })
    }
    const { expenseType } = this.state;
    if (expenseType.code === "MCD1001") {
      let fieldOID = "";
      expenseType.fields.some((item) => {
        if (item.messageKey === "public.assembly") {
          fieldOID = item.fieldOID;
          this.props.form.validateFields([fieldOID], { force: true });
          return true;
        }
        return false;
      });
    }
    // 可分摊金额处理
    this.getInvoiceTaxAmount();
    this.reRender();
    this.setState({
      isThan5000: value > 5000 ? false : true,
      promptThan300: (expenseType.code === 'MCD1094'&&value<=300)? false :true,
    });
  };

  //解决真实DOM延迟渲染问题
  reRender() {
    let { readOnly } = this.state;
    setTimeout(() => this.setState({ readOnly }), 10);
  }

  getFieldEnumerationList = () => {
    const { expenseType, nowExpense } = this.state;
    let fieldsCount = 0;
    let fields = [];
    console.log(nowExpense,'nowExpense');
    if (nowExpense && nowExpense.data) {
      fields = nowExpense.data;
    } else {
      fields = expenseType.fields;
    }
    fields= fields || [];
    let fieldLength = fields.length;
    fields.map((field, index) => {
      if (
        field.name === "接收人情况是否与申请单不同" &&
        field.isSwitchOn === null
      ) {
        field.isSwitchOn = true;
      }
      if (
        field.name === "参与人情况是否与申请单不同" &&
        field.isSwitchOn === null
      ) {
        field.isSwitchOn = true;
      }
      if (field.customEnumerationOID) {
        baseService
          .getCustomEnumerationsByOID(field.customEnumerationOID)
          .then((res) => {
            field.list = res.data ? res.data : [];
            fieldsCount++;
            if (fieldsCount === fieldLength) {
              fields.splice(index, 1, field);
              expenseType.fields = fields;
              if (nowExpense && nowExpense.data) {
                nowExpense.data = fields;
                this.setState({ nowExpense, expenseType });
              }
              this.setState({ expenseType });
            }
          });
      } else {
        fieldsCount++;
        if (fieldsCount === fieldLength) {
          fields.splice(index, 1, field);
          expenseType.fields = fields;
          if (nowExpense && nowExpense.data) {
            nowExpense.data = fields;
            this.setState({ nowExpense, expenseType });
          }
          this.setState({ expenseType });
        }
      }
    });
  };

  /**
   * 保存前的费用检查
   * @param values  当页通过组件验证的表单项
   * @return {Promise}
   */
  validate = (values) => {
    let expenseReport = this.props.expenseReport;
    return new Promise((resolve, reject) => {
      const {
        expenseType,
        nowCurrency,
        attachments,
        nowExpense,
        receiptList,
        unitPriceMode,
        businessCardConsumptions,
        expenseApportion,
        notShowFileList,
        electronicAttachments,
      } = this.state;
      const { profile, type, didiExpenseInfo } = this.props;
      // 错误数据
      let errorMessages = [];
      //初始化对象
      let target = nowExpense.invoiceOID
        ? JSON.parse(JSON.stringify(nowExpense))
        : {
            attachments: attachments,
            invoiceStatus: "INIT",
            readonly: false,
            recognized: false,
        };
      target.expenseTypeCode = expenseType.code;
      target.currencyCode = nowCurrency.currencyCode;
      target.expenseTypeName = expenseType.name;
      target.expenseTypeOID = expenseType.expenseTypeOID;
      target.expenseTypeId = expenseType.id;
      target.expenseTypeIconName = expenseType.iconName;
      target.expenseTypeKey = expenseType.messageKey;
      target.mileageAllowanceExpenseV2DTO =
        nowExpense.mileageAllowanceExpenseV2DTO;
      if (!expenseType.id) {
        errorMessages.push(messages("my-account.key72" /*请选择费用类型*/));
      }
      if (businessCardConsumptions.length > 0) {
        target.bankTransactionDetails = [];
        target.atlBankTransactions = businessCardConsumptions;
        let businessCardTotalAmount = businessCardConsumptions
          .reduce((pre, now) => {
            if (!now.relationMap) {
              now.relationMap = {};
            }
            const keys = Object.keys(now.relationMap);
            return (
              pre +
              keys.reduce((preKeyAmount, key) => {
                let keyAmount = 0;
                if (now.relationMap[key] && now.relationMap[key].length > 0) {
                  const relationArr = deepFullCopy(now.relationMap[key]);
                  keyAmount = relationArr.reduce((total, relation) => {
                    if (relation.amount !== 0 && relation.checked) {
                      return relation.amount + total;
                    } else {
                      return total + 0;
                    }
                  }, 0);
                  const reaultRelation = relationArr.filter(
                    (relation) => relation.checked
                  );
                  now.relationMap[key] = reaultRelation;
                }
                return preKeyAmount + keyAmount;
              }, 0)
            );
          }, 0)
          .toFixed(this.getInvoiceCurrencyPrecision());
        //商务卡配置以前是true或者false，现在改成1，2，3且做老数据兼容。
        if (
          profile["All.BusinessCardAmount.FeeAmount"] !== 1 &&
          this.props.type !== 2
        ) {
          // fix bug 26934
          if (
            this.checkFunctionProfiles("All.BusinessCardAmount.FeeAmount", [
              true,
              2,
              "true",
            ]) &&
            Math.abs(values.amount - businessCardTotalAmount) > Number.EPSILON
          ) {
            errorMessages.push(
              messages("my-account.key73" /*费用金额必须与商务卡消费金额一致*/)
            );
          }
          if (
            (!profile["All.BusinessCardAmount.FeeAmount"] ||
              profile["All.BusinessCardAmount.FeeAmount"] === 3) &&
            values.amount - businessCardTotalAmount > Number.EPSILON
          ) {
            errorMessages.push(
              messages(
                "my-account.key74" /*费用金额必须小于等于商务卡消费金额*/
              )
            );
          }

          businessCardConsumptions.some((item) => {
            if (item.posCurCod !== nowCurrency.currencyCode) {
              errorMessages.push(
                messages(
                  "my-account.key283"
                ) /*商务卡消费记录的币种应与费用币种一致*/
              );
              return true;
            }
          });
        }
        target.businessCardTotalAmount = Number(businessCardTotalAmount || 0);
      } else {
        target.bankTransactionDetails = [];
        target.atlBankTransactions = businessCardConsumptions;
        target.businessCardTotalAmount = 0;
      }
      let expenseInfo = nowExpense.invoiceOID
        ? nowExpense.data
        : expenseType.fields;
      let targetFields;
      if (expenseInfo) {
        targetFields = JSON.parse(JSON.stringify(expenseInfo));
      }
      console.log('targetFields>>>', targetFields);
      target.receiptList = receiptList;
      //将表单内容填入
      // console.log('values', values)
      Object.keys(values).map((key) => {
        let value = values[key];
        if (key === "createdDate") {
          if (type === 2) {
            // 如果是多条滴滴消费生成费用，createDate由每条滴滴消费的上车时间决定,所以validate函数里不返回createdDate，在saveExpense里添加
            if (didiExpenseInfo.length === 1) {
              let createdDate = deepFullCopy(value);
              target.createdDate = createdDate.utc().format();
            }
          } else {
            let createdDate = deepFullCopy(value);
            target.createdDate = createdDate.utc().format();
          }
        } else if (key === "payByCompany") {
          target.paymentType = value ? 1002 : 1001;
        } else if (key === "businessCardRemark") {
          target.bankTransactionDetail.remark = value;
        } else if (key === "viaPoints") {
          target.mileageAllowanceExpenseV2DTO &&
            (target.mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].viaPoints = value);
        } else if (key === "applicationNumber") {
          if (value && value.length > 0) {
            target.applicationNumber = value[0].businessCode;
          } else {
            target.applicationNumber = "";
          }
        } else {
          target[key] = value;
        }
        //循环查找fields值填入
        targetFields &&
          targetFields.map((field) => {
            if (
              key === field.fieldOID &&
              (this.props.type === 2 || field.editable)
            ) {
              // 滴滴打车的费用类型数据是直接从滴滴消费带过来的且不可编辑，所以这里加了一个type===2的判断条件
              if (this.props.type === 2) {
                if (field.messageKey === "vehicle.type") {
                  // 用车方式 2:专车，3:快车，5:豪华车
                  const vehicleType = {
                    专车: 2,
                    快车: 3,
                    豪华车: 5,
                  };
                  value = vehicleType[value];
                }
                if (
                  [
                    "company.real.pay",
                    "order.amount",
                    "personal.real.pay",
                    "coupon.amount",
                    "total.amount",
                    "normal.distance",
                  ].includes(field.messageKey)
                ) {
                  // 订单金额 订单金额=个人支付金额+优惠券, 公司支付, 个人支付, 优惠券抵扣, 总金额, 总里程
                  if (value) {
                    value = Number(value);
                  }
                }
                if (field.messageKey === "require.level") {
                  // 车型 100: '舒适型', 400: '商务型', 200: '豪华型', 500: '优选型', 600: '快车', 900: '优享型'
                  const carType = {
                    舒适型: 100,
                    商务型: 400,
                    豪华型: 200,
                    优选型: 500,
                    快车: 600,
                    优享型: 900,
                  };
                  value = carType[value];
                }
              }
              if (field.fieldType === "LONG" && field.name === "参与人数量") {
                // value = value;
                // console.log('111111111', JSON.stringify(value))
                value = Number(value);
              }
              if (field.fieldType === "PARTICIPANTS")
                // console.log('value=======', value)
                value = JSON.stringify(value);
              if (field.fieldType === "PARTICIPANT") {
                if (value && value.length > 0) {
                  value = JSON.stringify({
                    userOID: value[0].userOID,
                  });
                } else {
                  value = null;
                }
              }
              // 地区需要做特殊处理
              if (field.fieldType === "LOCATION") {
                value = value && value.key ? value.key : value;
              }

              if (target.mileageAllowanceExpenseV2DTO) {
                if (field.messageKey === "arrive.time") {
                  target.mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].arriveTime = value;
                }

                if (field.messageKey === "depart.time") {
                  target.mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].departTime = value;
                }

                if (field.messageKey === "depart.place") {
                  target.mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].start = JSON.parse(
                    value
                  );
                }

                if (field.messageKey === "destination") {
                  target.mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].end = JSON.parse(
                    value
                  );
                }
              }

              // console.log('value============', value)

              field.value = value;
              field.i18n = null;
              if (
                (field.list || field.fieldType === "CUSTOM_ENUMERATION") &&
                value &&
                Array.isArray(value) &&
                value.length > 0
              ) {
                field.value = value[0].value;
                field.list.map((item) => {
                  if (item.value === value[0].value)
                    field.valueKey = item.messageKey;
                });
              }
              //如果有值列表，则删除值列表数组
              if (field.list) delete field.list;
              //删除上面添加的属性
              delete target[key];
              return field;
            }
          });
      });
      if (!profile["All.FeeAmount.AllowZero"] && !target.amount) {
        if (this.props.type !== 1) {
          // 公务卡生成费用不限制金额不能为0
          if (
            this.props.type === 2 &&
            this.props.didiExpenseInfo.length === 1
          ) {
            errorMessages.push(messages("my-account.key75" /*金额不能为0*/));
          } else if (this.props.type !== 2) {
            errorMessages.push(messages("my-account.key75" /*金额不能为0*/));
          }
        }
      }
      // 2020-12-17 滴滴费用新增校验规则：滴滴费用的个人支付金额要大于等于公务卡消费的总金额，实际报销等于公务卡消费的总金额
      if (this.props.type === 2) {
        let personalPay = 0;
        targetFields.some((field) => {
          if (field.messageKey === "personal.real.pay") {
            personalPay = field.value;
            return true;
          }
        });
        if (target.businessCardTotalAmount > 0) {
          if (target.amount !== target.businessCardTotalAmount) {
            errorMessages.push("滴滴费用的实际报销要等于公务卡消费的总金额");
          }
          if (personalPay < target.businessCardTotalAmount) {
            errorMessages.push(
              "滴滴费用的个人支付金额要大于等于公务卡消费的总金额"
            );
          }
        }
        // else {
        //   if (target.amount > personalPay) {
        //     errorMessages.push('滴滴费用报销金额要小于等于个人支付金额');
        //   }
        // }
      }
      //第三方费用修改金额
      let thirdEditAmount =
        !this.props.readOnly &&
        expenseType.readonly &&
        expenseType.isAmountEditable &&
        expenseType.messageKey !== "private.car.for.public";
      if (
        thirdEditAmount &&
        !profile["All.FeeAmount.OrderAmount"] &&
        nowExpense.orderAmount < target.amount
      ) {
        errorMessages.push(
          messages("my-account.key76" /*金额不能大于原始金额*/)
        );
      }

      //当不提票时置理由为空，防止下次修改自动填上上次的值
      if (!target.invoiceInstead) {
        target.invoiceInsteadReason = null;
      }
      if (
        receiptList.length < 1 &&
        expenseType.invoiceRequired &&
        expenseType.pasteInvoiceNeeded
      ) {
        errorMessages.push(messages("my-account.key184") /*请添加发票*/);
      }
      // 展示且必填且未上传时提示
      if (
        electronicAttachments.length < 1 &&
        !notShowFileList.includes(expenseType.code) && this.isRequiredNewFile(expenseType)
      ) {
        errorMessages.push(messages("my-account.key20231205") /*请添加电子支付凭证*/);
      }

      // // 电子支付金额<费用行金额且没有关联申请单提示
      // let dianzizhifLessThanFlag = false;
      // // 无关联申请单
      // let noApplyFlag = false;
      // targetFields.forEach(item=>{
      //   if(item.messageKey === "dianzizhif"){
      //     // debugger
      //     if(Number(item.value) < nowExpense.amount){
      //       dianzizhifLessThanFlag = true;
      //     }
      //   }
      //   if(item.name === "无法提供电子支付凭证申请"){
      //     // debugger
      //     if(!item.value){
      //       noApplyFlag = true;
      //     }
      //   }
      // })
      // if (dianzizhifLessThanFlag && noApplyFlag) {
      //   errorMessages.push(messages("my-account.key20231227") /*需关联无法提供电子支付凭证申请*/);
      // }

      // 电子支付金额超过费用行金额 提示
      console.log('target.amount', target);
      let dianzizhifFlag = false;
      targetFields.forEach(item=>{
        if(item.messageKey === "dianzizhif"){
          // debugger
          if(Number(item.value) > target.amount){
            dianzizhifFlag = true;
          }
        }
      })
      if (dianzizhifFlag) {
        errorMessages.push(messages("my-account.key20231211") /*电子支付金额不得超过费用行金额*/);
      }

      if (receiptList && receiptList.length > 0) {
        let invoiceControl =
          profile["InvoiceControl.InvoiceAmount.FeeAmount.ALL.Equal"];
        let priceTaxAmount = 0;
        receiptList.map((item) => {
          item.fee = item.fee || 0;
          priceTaxAmount = addCalculate(
            priceTaxAmount,
            item.fee / 100 +
              (item.nonDeductibleAmount ? item.nonDeductibleAmount / 100 : 0)
          ); // 金额 = 价税合计 + 不可抵扣
        });
        if (invoiceControl === 0 || !invoiceControl) {
          if (Number(target.amount) > priceTaxAmount) {
            errorMessages.push(
              messages(
                "my-account.key78" /*费用金额必须小于等于发票的价税合计*/
              )
            );
          }
        } else if (invoiceControl === 2 || invoiceControl === true) {
          if (Number(target.amount) !== priceTaxAmount) {
            errorMessages.push(
              messages("my-account.key79" /*费用金额必须等于发票的价税合计*/)
            );
          }
        }
      }
      target.data = targetFields;
      target.data &&
        target.data.map((item) => {
          if (
            item.fieldType === "DATETIME" ||
            item.fieldType === "DATE" ||
            item.fieldType === "MONTH"
          ) {
            // 如果存在业务编码为start.time的时间类控件，填写时间需早于业务编码为end.time的同类型控件，如存在多个，向下找最近的进行校验
            if (item.messageKey === "start.time") {
              let startTime = item.value;
              let endTime = target.data.find((element) => {
                return (
                  element.messageKey === "end.time" &&
                  element.fieldType === item.fieldType &&
                  element.sequence > item.sequence
                );
              });
              if (
                endTime &&
                ((item.fieldType === "DATETIME" &&
                  moment(startTime).isAfter(endTime.value)) ||
                  (item.fieldType === "DATE" &&
                    moment(startTime).isAfter(endTime.value, "day")) ||
                  (item.fieldType === "MONTH" &&
                    moment(startTime).isAfter(endTime.value, "month")))
              ) {
                errorMessages.push(
                  `${item.name}${messages("my-account.key329") /*不可晚于*/}${
                    endTime.name
                  }`
                );
              }
            }
            item.value = item.value
              ? moment(item.value).subtract(-8, "hours").utc().format()
              : null;
          }
          if (item.messageKey === "prompt.key" && item.name === "里程单价") {
            item.value = Number(this.state.unitPrice);
          }
          return item;
        });
      if (target.invoiceCode && target.invoiceCode !== "") {
        target.invoiceCode = target.invoiceCode.toUpperCase();
      }
      target.baseCurrency = this.props.company.baseCurrency;
      target.updateRate =
        profile["web.expense.rate.edit.disabled"] !== "true" &&
        profile["web.expense.rate.edit.disabled"] !== true;
      target.attachments = attachments;
      target.electronicAttachments = electronicAttachments;
      /**
       * @desc 增加条件判断 编辑中的费用分摊行都释放。1：是否有分摊行权限，|| 2：分摊数据中是否有关联的申请单分摊行OID （待优化）
       */
      let isRelatedApplication = () => {
        return (
          expenseApportion &&
          expenseApportion.some((item) => !!item.applicationApportionmentId)
        );
      };
      if (
        (isRelatedApplication() || expenseType.erApportionEnabled) &&
        expenseReport &&
        expenseApportion &&
        !(profile["All.FeeAmount.AllowZero"] && !target.amount)
      ) {
        if (expenseApportion.length === 0) {
          errorMessages.push(
            messages("my-account.key241") /*分摊行数为0，不可保存费用*/
          );
        } else {
          let targetApportion = [];
          let expenseApportionAmount = 0;
          let amountZeroTip = true;
          let itemNullTip = true;
          let personNullTip = true;
          let expenseApportionProportion = 0;
          expenseApportion.map((apportion) => {
            let tempApportion = JSON.parse(JSON.stringify(apportion));
            if (tempApportion.amount === 0 || tempApportion.proportion === 0) {
              amountZeroTip &&
                errorMessages.push(
                  messages("my-account.key80" /*费用分摊项金额与比例不能为0*/)
                );
              amountZeroTip = false;
            }
            if (
              !tempApportion.costCenterItems ||
              tempApportion.costCenterItems.length === 0
            ) {
              itemNullTip &&
                errorMessages.push(
                  messages(
                    "my-account.key81" /*费用分摊中的明细信息不完整，请完善*/
                  )
                );
              itemNullTip = false;
            } else {
              let existCostCenterItems = false;
              tempApportion.costCenterItems.map((item) => {
                if (item.required && !item.costCenterItemOID) {
                  /*费用分摊中的明细信息不完整，请完善*/
                  errorMessages.push(
                    `${item.fieldName}:${messages(
                      "my-account.key81" /*费用分摊中的明细信息不完整，请完善*/
                    )}`
                  );
                  itemNullTip = false;
                }
                if (item.costCenterItemOID) {
                  existCostCenterItems = true;
                }
              });
              if (!existCostCenterItems) {
                itemNullTip &&
                  errorMessages.push(
                    messages(
                      "my-account.key81" /*费用分摊中的明细信息不完整，请完善*/
                    )
                  );
                itemNullTip = false;
              }
            }
            if (!tempApportion.personName) {
              personNullTip &&
                errorMessages.push(
                  messages("my-account.key82" /*费用确认人不能为空*/)
                );
              personNullTip = false;
            }
            tempApportion.amount =
              (tempApportion.amount * 100).toFixed(2) / 100;
            if (
              -1 < tempApportion.proportion &&
              tempApportion.proportion < 1 &&
              tempApportion.proportion
            ) {
              if (
                tempApportion.proportion.toString().split(".")[1].length > 4
              ) {
                tempApportion.proportion = parseFloat(
                  tempApportion.proportion.toFixed(4)
                );
              }
            }
            expenseApportionAmount += tempApportion.amount * 100;
            if (tempApportion.proportion) {
              expenseApportionProportion += mulCalculate(
                tempApportion.proportion,
                10000
              );
            }
            targetApportion.push(tempApportion);
          });
          expenseApportion.some((item) => {
            if (item.amount >= 0 !== expenseApportion[0].amount >= 0) {
              errorMessages.push(
                messages("my-account.key286") /*分摊金额的符号请保持一致*/
              );
              return true;
            }
          });
          //判断小数加有精度问题
          if (expenseApportionProportion !== 10000) {
            let precision = queryCurrencyPrecision(target.currencyCode);
            let actualApportionAmount =
              this.state.actualApportionAmount || target.amount;
            if (
              parseFloat((expenseApportionAmount / 100).toFixed(precision)) !==
              parseFloat(actualApportionAmount.toFixed(precision))
            ) {
              errorMessages.push(
                messages("my-account.key83" /*分摊比率和需等于100%*/)
              );
            } else {
              if (
                expenseApportion &&
                expenseApportion.length > 0 &&
                expenseApportionProportion > 9500 &&
                expenseApportionProportion < 15000
              ) {
                let tailNumber =
                  targetApportion[targetApportion.length - 1].proportion;
                targetApportion[
                  targetApportion.length - 1
                ].proportion = addCalculate(
                  (10000 - expenseApportionProportion) / 10000,
                  tailNumber
                );
              }
            }
          }
          //分摊行成本中心联动，如果选择了父成本中心，子成本中心不能为空
          let sonCostCenterIsNull = false;
          (targetApportion || []).map((item) => {
            !sonCostCenterIsNull &&
              (item.costCenterItems || []).map((costCenterItem) => {
                if (
                  costCenterItem.type === "father" &&
                  costCenterItem.costCenterItemOID
                ) {
                  //父成本中心有值
                  item.costCenterItems.map((costCenterItem) => {
                    if (
                      costCenterItem.type === "son" &&
                      !costCenterItem.costCenterItemOID
                    ) {
                      //子成本中心没有值
                      errorMessages.push(
                        messages("common.please.select") /*请选择*/ +
                          costCenterItem.fieldName
                      );
                      sonCostCenterIsNull = true;
                    }
                  });
                }
              });
          });
          target.expenseApportion = targetApportion;
        }
      } else {
        target.expenseApportion = [];
      }
      target.receiptList = receiptList;
      // zt 阶梯模式才有这些处理
      if (
        target.expenseTypeKey === "private.car.for.public" &&
        (!unitPriceMode ||
          (unitPriceMode && nowExpense.mileageAllowanceExpenseDTO))
      ) {
        let allowanceControl = profile["All.FeeAllowance.equal"];
        //3不做校验
        let orderAmount = target.orderAmount;
        if (allowanceControl === 3) {
        } else if (allowanceControl === 2 && orderAmount !== target.amount) {
          errorMessages.push(
            messages("my-account.key84" /*费用金额必须等于补贴金额*/)
          );
        } else if (
          (!allowanceControl || allowanceControl === 1) &&
          orderAmount < target.amount
        ) {
          errorMessages.push(
            messages("my-account.key85" /*费用金额不能大于补贴金额*/)
          );
        }
      }
      if (this.isRequiredFile() && attachments.length === 0) {
        if (expenseType.code === "MCD1027" || expenseType.code === "MCD1410") {
          errorMessages.push("请上传私车公用费用报告");
        }else if (["MCD1094", "MCD1147"].includes(expenseType.code)){
          errorMessages.push("超300元/月需额外提供话费账单明细");
        } else {
          errorMessages.push(messages("my-account.key86" /*请上传附件*/));
        }
      }
      if (errorMessages.length > 0) {
        reject();
        errorMessages.length === 1
          ? message.error(errorMessages)
          : message.error(
              errorMessages.map((item, index) => {
                return (
                  <p style={{ textAlign: "left", margin: "5px 0 0" }}>
                    {index + 1}: {item}{" "}
                  </p>
                );
              })
            );
        return !1;
      }
      resolve(target);
    });
  };
  // 获取原币金额和原币税额
  getInvoiceTaxAmount = () => {
    // 有发票 且有费用信息 且分摊金额需要去除税额
    const { getFieldValue,setFieldsValue } = this.props.form;
    let { profile } = this.props;
    let {
      receiptList,
      expenseType,
      invoiceFp,
      readOnly,
      nowExpense,
      auditAmountEditing,
    } = this.state;
    let invoiceUserFp = invoiceFp ? invoiceFp : profile; //用于始终跟着单据走的FP场景
    let amount =
      this.state.didiArr.length > 1 && this.state.didiArr[0].total
      ? this.state.didiArr[0].total
      : readOnly && !auditAmountEditing
        ? nowExpense.amount
        : Number(getFieldValue("amount"));
    console.log("amount333333333333", amount);
    if (
      expenseType &&
      expenseType.id &&
      invoiceUserFp["all.total.amount.apportionment"] === false &&
      !Number.isNaN(amount)
    ) {
      let fieldData = [];
      expenseType.fields &&
        expenseType.fields.map((item) => {
          //业务用途 报销类型 影响分摊金额
          if (
            ~["business.type", "helios.reimbursement.type"].indexOf(
              item.messageKey
            )
          ) {
            let businessTypeItem = deepFullCopy(item);
            businessTypeItem.value =
              getFieldValue(item.fieldOID) && getFieldValue(item.fieldOID)[0]
                ? getFieldValue(item.fieldOID)[0].value
                : undefined;
            fieldData.push(businessTypeItem);
          }
        });
      const params = {
        amount,
        receiptList,
        originalAmount: amount,
        currencyPrecision: this.getInvoiceCurrencyPrecision(), //金额精度
        expenseTypeId: expenseType.id,
        withReceipt: expenseType.pasteInvoiceNeeded,
        data: fieldData,
      };
      expenseService
        .getOriginalApprovedVat(params)
        .then((res) => {
          this.setState({
            actualApportionAmount: res.data.rows.vatInvoice
              ? res.data.rows.nonVATinclusiveAmount
              : "",
            taxRate: res.data.rows.taxRate,
            isWorthAmount: amount !== 0,
          });
        })
        .catch((e) => {
          errorMessage(e.response);
        });
    console.log("amount333333444444444444", amount);
    // setFieldsValue({amount})
    } else {
      this.setState({ actualApportionAmount: "", isWorthAmount: amount !== 0 });
    }
  };

  /**
   * 点击保存
   */
  handleSave = (didiExpenseArr = [], didiOrderInfo = {}) => {
    let { receiptConfigList, didiOrderId, isRelationDidi } = this.state;
    this.props.form.getFieldValue("invoiceTypeNo") &&
      receiptConfigList &&
      receiptConfigList.map((item) => {
        if (item.value !== "10") {
          this.props.form.validateFields([item.valueCode], { force: true });
        }
      });
    // if (this.props.type === 2) {
    //   // 新建滴滴费用类型，如果选中的滴滴消费记录为多个，不需要验证
    //   const didiOrderInfoArr = this.props.didiExpenseInfo || [];
    //   if (didiOrderInfoArr.length > 1) {
    //     this.validate(this.props.form.getFieldsValue()).then((expense) => {
    //       let expenseReport = this.props.expenseReport;
    //       if (expenseReport) {
    //         expense.expenseReportOID = expenseReport.expenseReportOID;
    //       }
    //       // v3 前端验证之后直接调用后台保存接口
    //       this.saveExpense(expense, didiExpenseArr, didiOrderInfo);
    //     });
    //     return false;
    //   }
    // }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.validate(values).then((expense) => {
          let expenseReport = this.props.expenseReport;
          if (expenseReport) {
            expense.expenseReportOID = expenseReport.expenseReportOID;
          }
          // v3 前端验证之后直接调用后台保存接口
          this.saveExpense(expense, didiExpenseArr, didiOrderInfo);
        });
      }
    });
  };
  /**
   * @description 后台返回错误信息处理
   * @param item 错误字段
   * */
  showErrorMessage = (item) => {
    if (!item.title || !item.message) {
      return item.title || item.message;
    }
    return `${item.title}:${item.message}`;
  };
  /**
   * 保存费用
   * @param expense 费用对象
   */
  saveExpense = (expense, didiExpenseArr = [], didiOrderInfo = {}) => {
    const { getFieldValue } = this.props.form;
    const { isRelationDidi, didiOrderId } = this.state;
    this.setState({ saving: true });
    expense.applicationNumbers = [];
    if(expense.expenseTypeCode === "MCD1199" || expense.expenseTypeCode === "MCD1419"){ //类型为出差市内交通-企业滴滴和AA/LSMCO-差旅交通费-企业滴滴校验
      const dayData = JSON.parse(
        expense.data.filter((e) => {
          return e.messageKey === "dateCombined";
        })[0].value
      );
      let valid = false;
      let didiCardArr= [];
      const initFlag =  this.state.didiArr.length !== 0;
      didiCardArr = initFlag ?  this.state.didiArr : (this.props.params.didiExpenseInfo || []);//不为新建费用时
      try{
        didiCardArr.map(i=>{
          const createdDate = i.departureTime;
          const {startDate, endDate} = dayData;
          console.log(endDate,createdDate,moment(endDate).diff(moment(createdDate),'days'))
          if(moment(endDate).diff(moment(createdDate),'days') < 0 || moment(createdDate).diff(moment(startDate),'days') < 0){
            valid=true;
            message.warning('费用发生日期须在差旅日期期间内');
            this.setState({ saving: false });
            throw Error();
          }
        })
      }catch(e){
      }

      if(valid){
        return;
      }
    }
    if (!expense.ownerOID) {
      expense.ownerOID =
        (this.props.owner || {}).userOID ||
        (this.props.expenseReport || {}).applicantOID ||
        this.props.agentOid ||
        this.props.user.userOID;
    }
    let companyPaidFieldOID;
    expense.data.map((item) => {
      if (item.fieldType === "COMPANY_PAID") {
        companyPaidFieldOID = item.fieldOID;
        item.value =
          typeof item.value === "boolean"
            ? item.value
              ? "1002"
              : "1001"
            : item.value;
        expense.paymentType = item.value; //为兼容老数据
      }
      if (item.fieldType === "ASSOCIATE_APPLICATION") {
        //为兼容老数据
        expense.applicationNumber = item.value;
        if (typeof item.value === "string") {
          expense.applicationNumbers.push(item.value);
        }
      }
    });
    expense.data.map((item) => {
      if (item.messageKey === "company.payment.type") {
        //公司已付控件为false时，该控件值清空保存
        if (companyPaidFieldOID && !getFieldValue(companyPaidFieldOID)) {
          item.value = undefined;
        }
      }
      if (item.value === null) {
        item.showValue = null;
      }
    });
    if (expense.atlBankTransactions) {
      if (
        expense.atlBankTransactions != null &&
        expense.atlBankTransactions.length == 0
      ) {
        expense.isOfficialCard = 0;
      } else {
        expense.isOfficialCard = 1; //公务卡费用
      }
    }
    if (this.props.officialCard) {
      let associateDTO = {};
      associateDTO.ids = this.props.params.params.ids;
      associateDTO.relations = this.props.params.params.relations;
      expense.isOfficialCard = 1;
      expense.associateDTO = associateDTO;
    }
    console.log("this.props.didiExpenseInfo", this.props.didiExpenseInfo);
    let didiOrderIds = [];
    if (this.props.type === 2 && this.props.didiExpenseInfo.length === 1) {
      // expense.orderId = this.props.didiExpenseInfo[0].orderId;
      const { form } = this.props;
      expense.data.forEach(item => {
        let fieldOID = item.fieldOID;
        let obj = {};
        switch (item.messageKey) {
          case "total.amount":
            obj = {};
            obj[fieldOID] = this.props.params.selectedTotal;
            obj.amount = this.props.params.selectedTotal
            console.log(obj, 'obj');

            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          default:
            break;
        }
      })
      didiOrderIds.push(this.props.didiExpenseInfo[0].orderId)
      expense.didiOrderIds = didiOrderIds
      console.log(expense,'expense111');

      expense.companyId = this.props.company && this.props.company.id;
    } else if (this.props.type === 2 && this.props.didiExpenseInfo.length > 1) {
      expense.didiOrderIds =  this.props.didiExpenseInfo.map(i => {
        return i.orderId
      })
      const { form } = this.props;

      console.log(expense, 'expense2222');
      console.log(this.props.didiExpenseInfo,'didiExpenseInfo8888');
      // expense.orderId = '';

      expense.companyId = this.props.company && this.props.company.id;
      expense.createdDate = this.props.didiExpenseInfo[0].departureTime;
      expense.amount = this.props.params.selectedTotal || 0;
      expense.data.forEach(item => {
        let fieldOID = item.fieldOID;
        let obj = {};
        switch (item.messageKey) {
          case "total.amount":
            obj = {};
            obj[fieldOID] = this.props.params.selectedTotal;
            obj.amount = this.props.params.selectedTotal
            console.log(obj, 'obj');

            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          default:
            break;
        }
      })
      expense.comment = this.state.didiRemark;
      // const didiExpenseArr = [];
      // didiExpenseArr = this.props.didiExpenseInfo
      // didiExpenseArr.push(expense);
      // 多条滴滴打车消费记录不能单独生成费用，要把所有的expense都存到一个数组里然后直接传给生成费用的接口
      // return -1;

    } else if (
      this.props.type === 3 &&
      expense.expenseTypeName.indexOf("滴滴") !== -1
    ) {
      expense.didiOrderIds = expense.didiOrderIds;
      expense.companyId = expense.companyID;
    }
    console.log('+++++++++++11');

    if (isRelationDidi && didiOrderIds) {
      expense.didiOrderIds = didiOrderIds;
      const carType = {
        '舒适型': 100,
        '商务型': 400,
        '豪华型': 200,
        '优选型': 500,
        '快车': 600,
        '优享型': 900,
      };
      expense.data && expense.data.map((item) => {
        if(expense[item.fieldOID]){
          if(item.messageKey == "require.level"){
            item.value = carType[expense[item.fieldOID]]
          }else {
            item.value = expense[item.fieldOID]
          }
        }
      });
    }
    console.log('+++++++++++');
    console.log(this.state.didiArr, 'this.state.didiArr');
    console.log(this.state.didiRelationAmount,'this.state.didiRelationAmount');

    if (this.state.didiArr.length > 0 && this.state.didiRelationAmount) {
      let total = this.state.didiRelationAmount
      const { form } = this.props;
      console.log(total, 'total');
      // if (expense.data[13]) {
      //   expense.data[13].value = total
      // }
      // if (expense.data[11]) {
      //   expense.data[11].value = total
      // }
      expense.data.forEach(item => {
        let fieldOID = item.fieldOID;
        let obj = {};
        switch (item.messageKey) {
          case "total.amount":
            obj = {};
            obj[fieldOID] = total;
            obj.amount = total
            console.log(obj, 'obj');

            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          default:
            break;
        }
      })
    }






    let isFinal = false;
    if (
      expense.expenseTypeCode === "MCD1010" ||
      expense.expenseTypeCode === "MCD1009" ||
      expense.expenseTypeName === "部门活动" ||
      expense.expenseTypeName === "其他工作餐费"
    ) {
      const expenseApportion = expense.expenseApportion;
      const hasFinalPerson = expenseApportion.filter((e) => {
        return e.finalPersonName;
      });
      // console.log('hasFinalPerson', hasFinalPerson)
      if (hasFinalPerson.length === expenseApportion.length) {
        isFinal = true;
      } else {
        isFinal = false;
        this.setState({ saving: false });
        message.warning("请填写GM/VP/Officer");
      }
    } else if (
      expense.expenseTypeName === "商务应酬" &&
      expense.amount > 5000
    ) {
      const hasNum = expense.data.filter((e) => {
        return e.name === "商务应酬申请单";
      });
      if (!hasNum[0].value) {
        isFinal = false;
        this.setState({ saving: false });
        message.warning("费用金额大于5,000时，请关联商务应酬申请单");
      } else {
        isFinal = true;
      }
    } else if (expense.expenseTypeCode === "MCD1043") {
      const startTime = expense.data.filter((e) => {
        return e.name === "租房开始月份";
      });
      const endTime = expense.data.filter((e) => {
        return e.name === "租房截止月份";
      });
      if (moment(endTime[0].value).diff(moment(startTime[0].value)) >= 0) {
        isFinal = true;
      } else {
        this.setState({ saving: false });
        message.warning("租房开始月份必须小于租房截止月份");
        isFinal = false;
      }
    } else {
      isFinal = true;
    }

    console.log("expense", expense);
    if (expense.expenseTypeCode === "MCD1047") {
      expense.data.map((item) => {
        if (item.messageKey === "mcd.car") {
          item.value = JSON.stringify(item.value);
        }
      });
    }
    if (expense.expenseTypeCode === "MCD1001") {
      expense.data.map((item) => {
        if (item.name === "参与人情况是否与申请单不同") {
          if (item.isSwitchOn === false) {
            item.showValue = "[]";
            item.value = "[]";
          }
          if (item.isSwitchOn === null) {
            if (item.value && item.value !== "[]") {
              item.isSwitchOn = true;
            }
          }
        }
      });
    }

    if (expense.expenseTypeCode === "MCD1003") {
      expense.data.map((item) => {
        if (item.name === "接收人情况是否与申请单不同") {
          if (item.isSwitchOn === false) {
            item.showValue = "[]";
            item.value = "[]";
          }
          if (item.isSwitchOn === null) {
            if (item.value && item.value !== "[]") {
              item.isSwitchOn = true;
            }
          }
        }
      });
    }

    if (
      [
        "MCD1018",
        "MCD1024",
        "MCD1214",
        "MCD1221",
        "MCD1229",
        "MCD1053",
      ].includes(expense.expenseTypeCode) &&
      this.state.feeAcknowledgersIsSwitch
    ) {
      let feeAcknowledgers = this.state.feeAcknowledgers;
      let showMessage = false;
      feeAcknowledgers.map((item) => {
        delete item.precent;
        if (item.userOid && item.amount) {
        } else {
          showMessage = true;
          this.setState({ saving: false });
          isFinal = false;
        }
      });
      if (showMessage) {
        message.warning("请填写姓名和金额后保存");
      }
    }
    // TES-1871
    if (
      [
        "MCD1054",
        "MCD1134",
        "MCD1213",
        "MCD1220",
        "MCD1228",
        "MCD1014",
        "MCD1039",
        "MCD1240",
      ].includes(expense.expenseTypeCode) &&
      expense.amount
    ) {
      const dayData = JSON.parse(
        expense.data.filter((e) => {
          return e.messageKey === "dateCombined";
        })[0].value
      );
      // https://pmo.mcd.com.cn/jira/browse/TES-2030
      // 如果上传了发票，并且发票编码存在01 08 200 010其中之一或更多
      // 就不需要判断是否填写了“酒店住宿未提供增值税专用发票说明”
      // 也不需要判断是否关联了“关联事先申请”
      const { receiptList } = this.state;
      let pass = false;
      // https://pmo.mcd.com.cn/jira/browse/TES-2272
      // 'MCD1014', 'MCD1134', 'MCD1054', 'MCD1039'如果是这四种费用，上传的发票都是“无票”发票编码为190
      // 就不需要判断是否填写了“酒店住宿未提供增值税专用发票说明”
      // 也不需要判断是否关联了“关联事先申请”
      // 2021-07-22 TES-2272新增'MCD1213', 'MCD1220', 'MCD1228'
      if (
        [
          "MCD1014",
          "MCD1134",
          "MCD1054",
          "MCD1039",
          "MCD1213",
          "MCD1220",
          "MCD1228",
          "MCD1240",
        ].includes(expense.expenseTypeCode)
      ) {
        let receipt190 = true; // 发票编号是否全是190
        receiptList.some((receipt) => {
          if (receipt.invoiceTypeNo !== "190") {
            receipt190 = false;
          }
          return !receipt190;
        });
        if (receipt190) {
          pass = true;
        }
      }
      if (receiptList && receiptList.length > 0) {
        receiptList.some((receipt) => {
          if (["01", "08", "200", "010","112"].includes(receipt.invoiceTypeNo)) {
            pass = true;
          }
          return pass;
        });
      }
      const num =
        moment(dayData.endDate).diff(dayData.startDate, "days") <= 1
          ? 1
          : moment(dayData.endDate).diff(dayData.startDate, "days");
      if (expense.amount > 400 * num) {
        const hotelNoInvoiceApply = expense.data.filter((e) => {
          return e.name === "酒店无专票申请";
        });
        if (!pass && !hotelNoInvoiceApply[0].value) {
          message.warning("酒店住宿未提供增值税专用发票，请关联事先申请单");
          this.setState({ saving: false });
          isFinal = false;
        }
      } else {
        const hotelNoInvoiceApply = expense.data.filter((e) => {
          return e.name === "酒店无专票申请";
        });
        const hotelNoComment = expense.data.filter((e) => {
          return e.name === "酒店住宿未提供增值税专用发票说明";
        });
        if (!pass && !hotelNoInvoiceApply[0].value) {
          if (!hotelNoComment[0].value) {
            message.warning(
              "酒店住宿未提供增值税专用发票，请说明无法提供增值税专用发票的原因"
            );
            this.setState({ saving: false });
            isFinal = false;
          }
        }
      }
    }

    const saveExpenseFinally = () => {
      console.log("expense", expense);
      // if (['MCD1018', 'MCD1024', 'MCD1214', 'MCD1221', 'MCD1229'].includes(expense.expenseTypeCode)) {
      //   if (this.state.feeAcknowledgers && this.state.feeAcknowledgersIsSwitch) {
      //     expense.feeAcknowledgers = this.state.feeAcknowledgers;
      //   } else if (this.state.feeAcknowledgers && !this.state.feeAcknowledgersIsSwitch) {
      //     expense.feeAcknowledgers = [{
      //       userOid: this.state.feeAcknowledgers[0].userOid,
      //       name: this.state.feeAcknowledgers[0].name,
      //       amount: expense.amount || expense.baseAmount
      //     }]
      //   }
      // }
      expenseService
        .saveExpense(expense)
        .then((res) => {
          if (this.props.type === 2) {
            this.props.resetDiDiPage && this.props.resetDiDiPage();
            // this.props.params.closeShow()
            this.setState({
              saving: false,
              showDiDiModal: false,
              didiModalInfo: "",
              didiArr:[],
            });
          } else {
            this.setState({ saving: false });
          }

          // 需补填税率
          if (res.data.code === "R_2002") {
            // 请补录税率
            message.error(messages("my-account.key87" /*请补录税率*/));
            this.setState({
              recordTaxRateConfig: true,
              recordTaxAmountConfig: true,
              recordNonVATinclusiveAmountConfig: true,
            });
            return !1;
          }
          // 保存失败 错误信息处理
          if (res.data.code !== "0000") {
            let errorList = res.data.rows.errorList;
            if (errorList.length > 0) {
              errorList.length === 1
                ? message.error(this.showErrorMessage(errorList[0]))
                : message.error(
                    errorList.map((item, index) => {
                      return (
                        <p style={{ textAlign: "left", margin: "5px 0 0" }}>
                          {index + 1} {this.showErrorMessage(item)}{" "}
                        </p>
                      );
                    })
                  );
            }
            return !1;
          }

          const expenseCode = this.state.expenseType.code;
          if ("MCD1010" === expenseCode || "MCD1009" === expenseCode) {
            if (
              (res.data.code === "0000" || res.data.message === "SUCCESS") &&
              null !== res.data.rows.successMessageList &&
              undefined !== res.data.rows.successMessageList &&
              res.data.rows.successMessageList.length !== 0
            ) {
              const successMsgList = res.data.rows.successMessageList;
              Modal.success({
                title: messages("enterprise-manage.key508" /*剩余额度提示*/),
                content: (
                  <div>
                    {successMsgList.map((item) => (
                      <p>{item}</p>
                    ))}
                  </div>
                ),
                onOk() {},
              });
            }
          }

          // 正常保存
          let { businessCardConsumptions, singleBusinessCards } = this.state;
          message.success(messages("common.save.success", { name: "" }));
          //如果是商务卡导入
          if (singleBusinessCards.length > 0) {
            businessCardConsumptions = [singleBusinessCards[0]];
            singleBusinessCards.splice(0, 1);
            //商务卡池中还有卡，继续导入

            this.setState(
              {
                businessCardConsumptions,
                singleBusinessCards,
                nowPage: "form",
                nowExpense: {},
                attachments: [],
                nowCurrency: {
                  rate: 1.0,
                  currencyCode: this.props.company.baseCurrency,
                },
                expenseType: {},
              },
              () => {
                this.props.form.resetFields();
                this.setValuesByBusinessCard();
              }
            );
          } else {
            this.onCancel(true);
          }
        })
        .catch((e) => {
          this.setState({ saving: false });
          errorMessage(e.response);
          //message.error(e.response.data.message)
        });
    };

    if (isFinal) {
      expense.baseAmount = expense.amount;
      if (
        [
          "MCD1018",
          "MCD1024",
          "MCD1214",
          "MCD1221",
          "MCD1229",
          "MCD1053",
        ].includes(expense.expenseTypeCode)
      ) {
        if (
          this.state.feeAcknowledgers &&
          this.state.feeAcknowledgersIsSwitch
        ) {
          expense.feeAcknowledgers = this.state.feeAcknowledgers;
        } else if (
          this.state.feeAcknowledgers &&
          !this.state.feeAcknowledgersIsSwitch
        ) {
          expense.feeAcknowledgers = [
            {
              userOid: this.state.feeAcknowledgers[0].userOid,
              name: this.state.feeAcknowledgers[0].name,
              amount: expense.amount || expense.baseAmount,
            },
          ];
        }
      } else {
        expense.feeAcknowledgers = [];
      }
      if (this.state.didiArr.length > 0) {
        expense.didiOrderIds =  this.state.didiArr.map(i => {
          return i.orderId
        })
      }

      console.log(expense,'...expense');
      expenseService
        .saveExpenseCheck({
          ...expense,
          expenseReportOID:
            this.props.expenseReport &&
            this.props.expenseReport.expenseReportOID
              ? this.props.expenseReport.expenseReportOID
              : null,
        })
        .then((res) => {
          let isModalOpen = false;
          let messageCount = 0;
          if (res.data.code === "0000") {
            let rows = res.data.rows;
            if (rows.length > 0) {
              let errorList = [];
              rows.map((item) => {
                errorList.push(item.errorList[0]);
              });
              errorList &&
                errorList.map((errorItem) => {
                  if (errorItem.message) {
                    messageCount++;
                  }
                });
              console.log("errorList", errorList);
              if (errorList && errorList.length > 0 && messageCount) {
                isModalOpen = true;
                Modal.confirm({
                  title: "信息提示",
                  content: (
                    <div>
                      {errorList.map((errorItem) => {
                        return (
                          <div key={errorItem.code}>{errorItem.message}</div>
                        );
                      })}
                    </div>
                  ),
                  onOk: () => saveExpenseFinally(),
                  okText: messages("common.yes") /*是*/,
                  cancelText: messages("common.no") /*否*/,
                  onCancel: () => {
                    this.setState({ saving: false });
                  },
                });
              }
            }
          }

          if (!isModalOpen) {
            saveExpenseFinally();
          }
        })
        .catch((e) => {
          this.setState({ saving: false });
          errorMessage(e.response);
          console.log("e.response.message", e.response.message);
          if (
            e.response.data.message ===
              "您填写的参与人数量与关联的商务应酬申请单中人数不一致，请重新在此页面填写参与人清单" ||
            e.response.data.message ===
              "您填写的接收人数量与关联的礼品申请单中人数不一致，请重新在此页面填写接收人清单"
          ) {
            const map = (item) => {
              if (item.name === "参与人情况是否与申请单不同") {
                return {
                  ...item,
                  isSwitchOn: true,
                };
              }
              if (item.name === "接收人情况是否与申请单不同") {
                return {
                  ...item,
                  isSwitchOn: true,
                };
              }
              return {
                ...item,
              };
            };
            this.setState(
              {
                nowExpense: {
                  ...this.state.nowExpense,
                  data: (this.state.nowExpense.data || []).map(map),
                },
                expenseType: {
                  ...this.state.expenseType,
                  fields: (this.state.expenseType.fields || []).map(map),
                },
              },
              () => {
                // this.props.form.validateFields([field.fieldOID], { force: true });
              }
            );
          }
        });
    }
  };

  //滴滴消费多条记录新增remark
  onRemarkChange = (e) => {
    console.log(e.target.value,'````');
    this.setState({
      didiRemark: e.target.value,
    });
  };

  /**
   * 多条滴滴打车消费生成费用
   * 关闭didiModal弹窗、关闭费用选择的抽屉、清空滴滴页面的selectedRowKeys
   */
  handleOnCreateExpense = () => {
    const { expenseType } = this.state;
    const { user, company, didiExpenseInfo, resetDiDiPage } = this.props;
    const didiExpenseArr = [];
    didiExpenseInfo.map((didiOrderInfo, didiInfoIndex) => {
      const formValueObj = {};
      expenseType.fields.map((field) => {
        formValueObj[field.fieldOID] = this.getFieldDefaultValue(
          field.fieldType,
          null,
          null,
          field,
          didiInfoIndex
        );
      });
      this.props.form.setFieldsValue(formValueObj);
      this.handleSave(didiExpenseArr, didiOrderInfo);
    });
    setTimeout(() => {
      console.log(didiExpenseArr,'didiExpenseArr222');
      console.log(didiExpenseInfo,'didiExpenseInfo2222');
      expenseService.saveDiDiExpense(didiExpenseInfo).then((res) => {
        console.log("res", res);
        if (res.status === 200) {
          if (res.data.code === 200) {
            resetDiDiPage();
            this.setState(
              {
                showDiDiModal: false,
                didiModalInfo: "",
              },
              () => {
                message.success(res.data.msg);
              }
            );
          } else {
            message.error(res.data.msg);
          }
        } else {
          message.error("创建费用失败，请重新操作");
        }
      });
    }, 0);
  };

  /**
   * 切换费用类型
   * @param expenseType
   */
  handleSelectExpenseType = (expenseType) => {
    let { businessCardConsumptions, nowExpense } = this.state;
    const { type, didiExpenseInfo } = this.props.params;
    console.log(this.props,'this.props``');
    let handleBiz = () => {
      if (type !== 2 || didiExpenseInfo.length === 1) {
        this.setState({ nowPage: "form" });
      }
      if (expenseType.id) {
        this.setState({ loading: true });
      }
      expenseType.id &&
        baseService.getExpenseTypeById(expenseType.id).then((res) => {
          res.data.fields.sort((a, b) => a.sequence > b.sequence || -1);
          let willSet = {};
          if (type === 2 && didiExpenseInfo.length > 1) {
            willSet = {
              expenseType: res.data,
              loading: false,
              nowPage: "form",
            };
            //     showDiDiModal: true,
            //     didiModalInfo: (
            //       <div style={{ color: "rgba(0, 0, 0, 0.65)" }}>
            //         是否将选中的滴滴消费记录转成&nbsp;&nbsp;
            //         <span
            //           style={{ fontWeight: "bold", color: "rgba(0, 0, 0, 1)" }}
            //         >
            //           {expenseType.name}
            //         </span>
            //         <Input
            //           style={{ marginTop: "20px" }}
            //           placeholder={messages(
            //             "my-account.key128" /*请输入备注，非必填*/
            //           )}
            //           maxLength="200"
            //           onChange={this.onRemarkChange}
            //           ref={(input) => (this.remark = input)}
            //         />
            //       </div>
            //     ),
            //   };
          } else {
            willSet = {
              expenseType: res.data,
              loading: false,
            }
          }
          console.log(res.data,'res.data');
          if (nowExpense.invoiceOID) {
            // 已经生成费用的费用切换费用类型
            nowExpense.data = res.data.fields;
            willSet.nowExpense = nowExpense;
          }
          // 用户切换费用类型的时候清空选中的公务卡消费明细
          if (businessCardConsumptions && businessCardConsumptions.length > 0) {
            businessCardConsumptions = [];
            willSet.businessCardConsumptions = businessCardConsumptions;
          }
          if (expenseType.name.indexOf("滴滴") !== -1) {
            this.setState({ isDiDiChange: true });
            let fields = []
            if(this.state.isRelationDidi && this.state.lastExpenseDetail.fields){
              fields = nowExpense.data.map((item)=>{
                this.state.lastExpenseDetail.fields.some((lastExpenseDetailItem)=>{
                  if(lastExpenseDetailItem.messageKey == item.messageKey){
                    item.value = lastExpenseDetailItem.value
                    return true
                  }
                })
                return item
              })
              nowExpense.data = fields;
            }
            willSet.nowExpense = nowExpense;
          }
          this.setState(willSet, () => {
            //如果有商务卡，则自动填充金额和币种
            if (businessCardConsumptions.length > 0) {
              this.setValuesByBusinessCard();
            }
            this.getFieldEnumerationList();
            this.getInvoiceTaxAmount();
            //根据发票获取费用默认值
            this.getDefaultValueByInvoice();
            this.updateShowAssiciateApplication();
          });
        });
    };
    this.handleReceiptByExpenseTypeChangeAsync(expenseType).then((result) => {
      if (result) {
        handleBiz();
      } else {
        this.setState({ nowPage: "type", typeSource: "expenseType" });
      }
    });
  };

  // 修改里程
  handleChangeMileage = (mileage) => {
    const { unitPriceMode } = this.state;
    const { getFieldValue } = this.props.form;
    let unitPrice = 0;
    if (unitPriceMode && !isNaN(mileage)) {
      const priceFile = this.state.nowExpense.data.filter(
        (field) => field.messageKey === "unit.price"
      )[0];
      priceFile && (unitPrice = getFieldValue(priceFile.fieldOID));
      this.props.form.setFieldsValue({ amount: unitPrice * mileage });
    }
  };
  // 修改里程单价
  handleChangeUnitPrice = (unitPrice) => {
    const { unitPriceMode } = this.state;
    const { getFieldValue } = this.props.form;
    let mileageVal = 0;
    if (unitPriceMode && !isNaN(unitPrice)) {
      const mileageFile = this.state.nowExpense.data.filter(
        (field) =>
          field.messageKey === "ER_KM" || field.messageKey === "mileage"
      )[0];
      mileageFile && (mileageVal = getFieldValue(mileageFile.fieldOID));
      this.props.form.setFieldsValue({ amount: mileageVal * unitPrice });
    }
  };
  getInvoiceCurrencyPrecision = () => {
    let { getFieldsValue, getFieldValue } = this.props.form;
    let { nowExpense } = this.props;
    let invoiceCurrencyCode = getFieldsValue().hasOwnProperty(
      "invoiceCurrencyCode"
    )
      ? getFieldValue("invoiceCurrencyCode")
      : nowExpense
      ? nowExpense.currencyCode
      : "";
    return queryCurrencyPrecision(invoiceCurrencyCode);
  };

  //修改值列表
  handleEnumerationChange = (messageKey) => {
    if (~["business.type", "helios.reimbursement.type"].indexOf(messageKey)) {
      //修改业务用途或报销类型时，需要重新获取分摊金额
      this.getInvoiceTaxAmount();
    }
  };

  onSwitchChange = (field, isSwitchOn) => {
    // console.log("field==========", field, this.props.form.getFieldsValue().amount)
    // https://pmo.mcd.com.cn/jira/browse/TES-2185
    const { expenseType } = this.state;
    const currentAmount = this.props.form.getFieldValue("amount") || 0;
    if (
      expenseType.code === "MCD1001" &&
      !isSwitchOn &&
      currentAmount <= 5000
    ) {
      let listValueStr = ""; // 参与人情况是否与申请单不同的值
      let requestValueStr = ""; // 商务应酬申请单的值
      expenseType.fields.map((field) => {
        if (field.messageKey === "public.assembly") {
          listValueStr = this.props.form.getFieldValue(field.fieldOID) || "[]";
        }
        if (field.name === "商务应酬申请单") {
          requestValueStr = this.props.form.getFieldValue(field.fieldOID);
        }
      });
      if (!requestValueStr) {
        if (listValueStr.length > 0) {
          // 因为这个公共组件的value为空时，组件下面有红色文本提示，不需要再出现提示
          message.warning(
            "由于您的商务应酬金额小于等于5000，且未关联商务应酬申请单，请填写商务应酬参与人员清单。"
          );
        }
      }
    }
    const map = (item) => {
      if (item.fieldOID === field.fieldOID) {
        if (item.name === "参与人情况是否与申请单不同") {
          if (this.state.isThan5000) {
            let isSwitchPublic = false;
            this.state.expenseType &&
              this.state.expenseType.fields.map((item) => {
                if (
                  item.name === "商务应酬申请单" ||
                  item.name === "礼品申请单"
                ) {
                  let data = this.props.form.getFieldsValue()[item.fieldOID];
                  if (data) {
                    isSwitchPublic = true;
                  }
                }
              });
            if (isSwitchPublic) {
              return {
                ...item,
                isSwitchOn,
              };
            } else {
              return {
                ...item,
                isSwitchOn: true,
              };
            }
          }
        }
        if (item.name === "接收人情况是否与申请单不同") {
          this.setState({ dontNeed5000: true });
        }
        if (item.name === "无票/遗失发票/专票无法抵扣") {
          const formValueObj = {};
          formValueObj[field.fieldOID] = undefined;
          this.props.form.setFieldsValue(formValueObj);
        }
        if(!isSwitchOn&&item.switchText=='无票/遗失发票/专票无法抵扣'){
          const formValueObj = {};
          formValueObj[field.fieldOID] = undefined;
          this.props.form.setFieldsValue(formValueObj)
        }
        return {
          ...item,
          isSwitchOn,
        };
      }
      return item;
    };
    this.setState(
      {
        nowExpense: {
          ...this.state.nowExpense,
          data: (this.state.nowExpense.data || []).map(map),
        },
        expenseType: {
          ...this.state.expenseType,
          fields: (this.state.expenseType.fields || []).map(map),
        },
      },
      () => {
        this.props.form.validateFields([field.fieldOID], { force: true });
      }
    );
  };


  /**
   * 渲染表单项
   * @param field
   * @param isSubsidyType 是否为差补费用
   * @return {XML}
   */
  switchField = (field, isSubsidyType = false, isMile) => {
    let currencyPrecision = this.getInvoiceCurrencyPrecision();
    const { isWithTime, expenseReport } = this.props;
    const { expenseType, ownerOID, lovEditable } = this.state;
    const disableMile = isMile && !lovEditable;
    /**
     * fixes: https://pmo.mcd.com.cn/jira/browse/TES-1628
     *
     * 把费用详情的data里一些本该有值的字段返回的null，这边的处理方式
     * 是把费用类型的fields里的字段拿过来。
     * 实际上最好还是费用详情接口解决返回值为null的问题。
     */
    let fieldInExpenseType = {};
    try {
      fieldInExpenseType = this.state.expenseTypeCache.fields.find((item) => {
        return item.fieldOID === field.fieldOID;
      });
    } catch (e) {}

    switch (field.fieldType) {
      case "POSITIVE_INTEGER":
        return (
          <InputNumber
            style={{ width: "100%" }}
            precision={0}
            disabled={!field.editable || disableMile}
            min={1}
            placeholder={field.placeholder || messages("common.please.enter")}
          />
        );
      case "LONG":
        return (
          <InputNumber
            style={{ width: "100%" }}
            precision={0}
            disabled={!field.editable || disableMile}
            placeholder={field.placeholder || messages("common.please.enter")}
          />
        );
      case "DOUBLE":
        // 里程
        if (field.messageKey === "ER_KM" || field.messageKey === "mileage") {
          return (
            <InputNumber
              min={0}
              precision={2}
              style={{ width: "100%" }}
              disabled={!field.editable || disableMile}
              placeholder={field.placeholder || messages("common.please.enter")}
              onChange={this.handleChangeMileage}
            />
          );
        }
        // 单价模式里程补贴单价由fp控制
        if (this.state.unitPriceMode && field.messageKey === "unit.price") {
          let { expenseType } = this.state;
          let { unitPriceRange } = this.state;
          // 参考单价 file
          let referentPriceFile =
            expenseType.fields.filter(
              (field) => field.messageKey === "reference.price"
            )[0] || {};
          let referentPriceFileValue = this.getFieldDefaultValue(
            referentPriceFile.fieldType,
            referentPriceFile.value,
            referentPriceFile.showValue
          );
          return (
            <InputNumber
              min={
                unitPriceRange > 100
                  ? 0
                  : (1 - unitPriceRange / 100) * referentPriceFileValue
              }
              precision={currencyPrecision}
              style={{ width: "100%" }}
              step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
              max={referentPriceFileValue * (1 + unitPriceRange / 100)}
              disabled={!unitPriceRange || disableMile}
              placeholder={field.placeholder || messages("common.please.enter")}
              onChange={this.handleChangeUnitPrice}
            />
          );
        }
        if (field.name === "总金额") {
          return (
            <InputNumber
              min={0}
              precision={currencyPrecision}
              style={{ width: "100%" }}
              step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
              disabled
              placeholder={field.placeholder || messages("common.please.enter")}
            />
          );
        }
        return (
          <InputNumber
            min={0}
            precision={currencyPrecision}
            style={{ width: "100%" }}
            step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
            disabled={
              !field.editable ||
              field.messageKey === "unit.price" ||
              field.messageKey === "order.amount" ||
              disableMile
            }
            placeholder={field.placeholder || messages("common.please.enter")}
            // onChange={(value) => this.changePrice(field, value)}
            onChange={(value) => this.handleChangeInput(field, value)}            
          />
        );
      case "TEXT":
        if (field.customEnumerationOID) {
          return field.list ? (
            <Searcher
              method="get"
              searcherItem={{
                title: messages("my-account.key88" /*值列表*/),
                url: `${config.baseUrl}/api/custom/enumerations/${field.customEnumerationOID}/items/v2`,
                key: "value",
              }}
              listExtraParams={{
                keyword: "",
                page: 0,
                size: 30,
              }}
              single
              isNeedToPage
              labelKey="messageKey"
              placeholder={
                field.placeholder || messages("common.please.select")
              }
            />
          ) : (
            <Spin size="small" />
          );
        } else {
          if (field.messageKey === "dateCombined") {
            return (
              <DateCombined
                disabled={!field.editable || disableMile}
                isSubsidyType={isSubsidyType}
                daysComputeMode={Number(
                  (field.config || {}).daysComputeMode || 1
                )}
              />
            );
          }
          if (field.messageKey === "prompt.key") {
            return (
              <InputNumber
                style={{ width: "100%" }}
                disabled
                formatter={(value) =>
                  `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                }
                placeholder={messages("common.please.enter")}
              />
            );
          }
          if (field.messageKey === "public.assembly") {
            let isSwitchPublic = false;
            this.state.expenseType &&
              this.state.expenseType.fields.map((item) => {
                if (
                  item.name === "商务应酬申请单" ||
                  item.name === "礼品申请单"
                ) {
                  let data = this.props.form.getFieldsValue()[item.fieldOID];
                  if (data) {
                    isSwitchPublic = true;
                  }
                }
              });
            console.log(
              "expenseType.fields",
              isSwitchPublic,
              this.state.isThan5000,
              this.state.dontNeed5000
            );
            return (
              <SwitchWrapper
                isHidden={field.isHidden}
                switchText={field.switchText}
                isSwitchChecked={
                  this.state.expenseType.code === "MCD1001"
                    ? field.isSwitchOn
                    : this.state.expenseType.code === "MCD1003"
                    ? field.isSwitchOn
                    : field.isSwitchOn
                }
                onSwitchChange={this.onSwitchChange}
                fieldInfo={deepFullCopy(field)}
              >
                <UnifiedTable
                  {...omit(field, "value")}
                  {...omit(fieldInExpenseType, "value")}
                  formDataId={this.state.nowExpense.invoiceOID}
                  excleType={
                    this.state.expenseType.code === "MCD1001"
                      ? 1
                      : this.state.expenseType.code === "MCD1003"
                      ? 2
                      : undefined
                  }
                  pkId={this.state.nowExpense.expenseTypeId}
                />
              </SwitchWrapper>
            );
          }
          if (field.messageKey === "mcd.car") {
            let { expenseReport } = this.props;
            let employeeId = null;
            expenseReport &&
              expenseReport.custFormValues &&
              expenseReport.custFormValues.map((item) => {
                if (item.fieldName === "费用确认人") {
                  employeeId = item.valueCode;
                }
              });
            console.log("expenseReport", expenseReport);
            return (
              <Chooser
                single
                placeholder={messages("common.please.select")}
                labelKey="carNumber"
                valueKey="id"
                type="mcd_car"
                listExtraParams={
                  this.state.expenseType.code === "MCD1047"
                    ? {
                        employeeId,
                        userOid: this.props.agentOid || this.props.user.userOID,
                      }
                    : {}
                }
              />
            );
          }
          return (
            <Input
              disabled={!field.editable || disableMile}
              placeholder={field.placeholder || messages("common.please.enter")}
            />
          );
        }
      case "CUSTOM_ENUMERATION":
        let searcherItem = {
          title: messages("my-account.key88" /*值列表*/),
          url: `${config.baseUrl}/api/custom/enumerations/${field.customEnumerationOID}/items/v2`,
          key: "value",
        };
        let listExtraParams = {
          keyword: "",
          page: 0,
          size: 30,
        };
        return field.list ? (
          <Searcher
            method="get"
            searcherItem={searcherItem}
            listExtraParams={listExtraParams}
            single
            isNeedToPage
            labelKey="messageKey"
            placeholder={field.placeholder || messages("common.please.select")}
            onChange={() => this.handleEnumerationChange(field.messageKey)}
          />
        ) : (
          <Spin size="small" />
        );
      case "START_DATE_AND_END_DATE":
        return (
          <DateCombined
            onRef={(ref) => {
              this.dateCombinedRef = ref
            }}
            disabled={!field.editable || disableMile}
            isNeedTime={isWithTime && isSubsidyType}
            isSubsidyType={isSubsidyType}
            daysComputeMode={Number((field.config || {}).daysComputeMode || 1)}
            onChange={this.handleStartEndDateChange}
          />
        );
      case "DATE":
        return (
          <DatePicker
            disabled={!field.editable || disableMile}
            getCalendarContainer={this.getPopupContainer}
            style={{ width: "100%" }}
            placeholder={field.placeholder || messages("common.please.select")}
          />
        );
      case "MONTH":
        return (
          <MonthPicker
            disabled={!field.editable || disableMile}
            style={{ width: "100%" }}
            placeholder={field.placeholder || messages("common.please.select")}
          />
        );
      case "DATETIME":
        return (
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            disabled={!field.editable || disableMile}
            getCalendarContainer={this.getPopupContainer}
            style={{ width: "100%" }}
            placeholder={field.placeholder || messages("common.please.select")}
          />
        );
      case "GPS":
        return (
          <Location
            disabled={!field.editable || disableMile}
            placeholder={field.placeholder || messages("common.please.select")}
          />
        );
      case "LOCATION":
        return (
          <Selector
            type="city"
            params={{
              vendorType: "standard",
              language: this.props.language.code,
            }}
            disabled={!field.editable || disableMile}
            placeholder={
              !field.editable || disableMile
                ? "-"
                : field.placeholder || messages("common.please.select")
            }
          />
        );
      case "PARTICIPANTS":
        let chooserItem = deepFullCopy(chooserData["expense_participants"]);
        chooserItem.title = messages("my-account.key162", {
          arg1: field.name,
        }) /*选择{arg1}*/;
        let selectRange = (field.config || {}).participantsRange || 3;
        let params = {
          selectRange: expenseReport
            ? selectRange
            : ~[4, 5].indexOf(selectRange)
            ? 3
            : selectRange,
          expenseReportOId: expenseReport
            ? expenseReport.expenseReportOID
            : null,
          ownerOId: ownerOID,
        };
        return (
          <Chooser
            disabled={!field.editable || disableMile}
            selectorItem={chooserItem}
            newline
            labelKey="fullName"
            valueKey="userOID"
            listExtraParams={params}
            placeholder={field.placeholder || messages("common.please.select")}
          />
        );
      case "PARTICIPANT":
        let chooserItemUser =
          field.name === "公司市场部经理/督导"
            ? deepFullCopy(chooserData["user_lsm_or_msmp"])
            : field.name === "CBI部门确认人"
            ? deepFullCopy(chooserData["cbi_people"])
            : deepFullCopy(chooserData["user"]);
        chooserItemUser.title = messages("my-account.key162", {
          arg1: field.name,
        }) /*选择{arg1}*/;
        console.log("field===============", this);
        let companyOID = undefined;
        if (this.props.expenseReport) {
          let companyData = this.props.expenseReport.custFormValues.filter(
            (e) => {
              return e.fieldName === "费用承担公司";
            }
          );
          companyOID = companyData[0].value;
        } else {
          companyOID = this.props.company.companyOID;
        }
        return (
          <Chooser
            disabled={!field.editable || disableMile}
            selectorItem={chooserItemUser}
            single
            labelKey="fullName"
            valueKey="userOID"
            placeholder={field.placeholder || messages("common.please.select")}
            listExtraParams={
              field.name === "公司市场部经理/督导"
                ? {
                    companyOID: companyOID,
                  }
                : {}
            }
          />
        );
      case "COMPANY_PAID":
      case "BOOLEAN":
        return (
          <Switch
            onChange={(value) => this.handleChangeSwitch(value, field)}
            disabled={!field.editable || disableMile}
          />
        );
      case "ASSOCIATE_APPLICATION":
        let selectorItem = deepFullCopy(chooserData["my_request"]);
        const { expenseType } = this.state;
        selectorItem.url = `${config.baseUrl}/api/applications/invoice/refer?expenseTypeId=${expenseType.id}`;
        console.log(
          "fieldfieldfieldfieldfieldfieldfieldfieldfieldfieldfield",
          field
        );
        return (
          <SwitchWrapper
            isHidden={field.isHidden}
            switchText={field.switchText}
            isSwitchChecked={field.isSwitchOn}
            onSwitchChange={this.onSwitchChange}
            fieldInfo={field}
          >
            <Chooser
              onRef={(ref) => {
                this.chooser = ref
              }}
              selectorItem={selectorItem}
              disabled={
                field.applicationSource === 0 || !field.editable || disableMile
              }
              listExtraParams={{
                applicantOID: this.state.ownerOID,
                fieldOID: field.fieldOID,
                startDate: this.state.startDate,
                endDate: this.state.endDate,
                invoiceDate: this.state.nowDate,
              }}
              labelKey="businessCode"
              valueKey="businessCode"
              onlyNeed="businessCode"
              single
              placeholder={
                field.placeholder || messages("common.please.select")
              }
            />
          </SwitchWrapper>
        );
    }
  };

  //修改开始结束日期
  handleStartEndDateChange = (value) => {
    const { setFieldsValue, getFieldValue } = this.props.form;
    const { expenseType } = this.state;
    let dateObj = JSON.parse(value || "{}");
    let startDate = dateObj.startDate
      ? moment(dateObj.startDate).format("YYYY-MM-DD")
      : undefined;
    let endDate = dateObj.endDate
      ? moment(dateObj.endDate).format("YYYY-MM-DD")
      : undefined;
    let createdDate = moment(getFieldValue("createdDate")).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    if (startDate && endDate && expenseType.timeSupported) {
      startDate += createdDate.slice(10);
      endDate += createdDate.slice(10);
    }
    this.setState({
      startDate,
      endDate,
    });
    console.log("expenseType", expenseType);
    if(expenseType.code === "MCD1199" || expenseType.code === "MCD1419"){ //类型为企业滴滴日期不关联
      return;
    }
    if (expenseType.dateLinkageValue === "115_start_date") {
      setFieldsValue({
        createdDate: startDate ? moment(startDate) : undefined,
      });
    } else if (expenseType.dateLinkageValue === "115_end_date") {
      setFieldsValue({ createdDate: endDate ? moment(endDate) : undefined });
    }
  };

  /**
   * 表单项规则
   * @param field
   * @returns {Array}
   */
  getFieldRules = (field, list) => {
    switch (field.fieldType) {
      case "TEXT":
        if (field.messageKey === "public.assembly") {
          // 是公用列表
          if (field.isHidden) {
            // 展示了“是否显示组件关联开关”
            if (field.isSwitchOn) {
              // 显示这个表单项（“是否显示组件关联开关”为true）
              if (field.required) {
                // 这个表单项的必填为true
                const { expenseType } = this.state;
                const currentAmount = this.props.form.getFieldValue("amount");
                let messageStr = "请填写完整";
                if (expenseType.code === "MCD1001" && currentAmount <= 5000) {
                  // 商务应酬费用的公共列表“参与人情况是否与申请单不同”的提示信息
                  let requestValueStr = ""; // 商务应酬申请单的值
                  expenseType.fields.some((field) => {
                    if (field.name === "商务应酬申请单") {
                      requestValueStr = this.props.form.getFieldValue(
                        field.fieldOID
                      );
                      return true;
                    }
                  });
                  if (!requestValueStr) {
                    // https://pmo.mcd.com.cn/jira/browse/TES-2185
                    messageStr =
                      "由于您的商务应酬金额小于等于5000，且未关联商务应酬申请单，请填写商务应酬参与人员清单。";
                  }
                }
                return [
                  {
                    validator: (rule, value, callback) => {
                      if ([null, "[]"].includes(value)) {
                        callback(messageStr);
                      } else {
                        callback();
                      }
                    },
                  },
                ];
              } else {
                // 表单项不是必填
                return [];
              }
            } else {
              // 不显示这个表单项
              return [];
            }
          } else {
            // 不展示“是否显示联动开关”
            if (field.required) {
              // 表单项必填
              const { expenseType } = this.state;
              const currentAmount = this.props.form.getFieldValue("amount");
              let messageStr = "请填写完整";
              if (expenseType.code === "MCD1001" && currentAmount <= 5000) {
                // 商务应酬费用的公共列表“参与人情况是否与申请单不同”的提示信息
                let requestValueStr = ""; // 商务应酬申请单的值
                expenseType.fields.some((field) => {
                  if (field.name === "商务应酬申请单") {
                    requestValueStr = this.props.form.getFieldValue(
                      field.fieldOID
                    );
                    return true;
                  }
                });
                if (!requestValueStr) {
                  // https://pmo.mcd.com.cn/jira/browse/TES-2185
                  messageStr =
                    "由于您的商务应酬金额小于等于5000，且未关联商务应酬申请单，请填写商务应酬参与人员清单。";
                }
              }
              return [
                {
                  validator: (rule, value, callback) => {
                    if ([null, "[]"].includes(value)) {
                      callback(messageStr);
                    } else {
                      callback();
                    }
                  },
                },
              ];
            } else {
              // 表单项不必填
              return [];
            }
          }
        }
        if (field.messageKey === "mcd.car") {
          return [];
        }
        if (field.customEnumerationOID) {
          return [];
        } else {
          if (field.messageKey === "dateCombined") {
            return [];
          }
          if (field.messageKey === "public.assembly") {
            // TODO 总行数限制2000
            return [];
          }
          // if (field.name === '酒店住宿未提供增值税专用发票说明') {
          //   return [{
          //     validator: (rule, value, callback) => {
          //       // console.log("this.state", this.props.form.getFieldsValue(), list, value)
          //       const dayData = list.filter(e => {
          //         return e.messageKey === 'dateCombined'
          //       });
          //       const hotelNoInvoiceApply = list.filter(e => {
          //         return e.name === '酒店无专票申请'
          //       })
          //       let hotalValue = this.props.form.getFieldsValue()[hotelNoInvoiceApply[0].fieldOID];
          //       let dayValue = JSON.parse(this.props.form.getFieldsValue()[dayData[0].fieldOID]);
          //       const num = moment(dayValue.endDate).diff(dayValue.startDate, 'days') <= 1 ? 1 : moment(dayValue.endDate).diff(dayValue.startDate, 'days');
          //       // console.log('111111', dayValue.endDate, dayValue.startDate)
          //       if (this.props.form.getFieldsValue()['amount'] <= 400 * num) {
          //         if (!hotalValue) {
          //           if ([null, ''].includes(value)) {
          //             callback('请输入');
          //           } else {
          //             callback();
          //           }
          //         } else {
          //           callback();
          //         }
          //       } else {
          //         callback();
          //       }
          //     }
          //   }]
          // }
          return [
            {
              max: 50,
              message: messages("common.max.characters.length", { max: 50 }),
            },
          ];
        }
      default:
        return [];
    }
  };

  /**
   * 图片上传成功
   */
  uploadSuccess = (response) => {
    let { nowExpense, invoiceList } = this.state;
    invoiceList.map((item) => {
      item.invoiceOID === nowExpense.invoiceOID &&
        item.invoiceView &&
        (item.invoiceView.attachments = response);
      return item;
    });
    response.map((item) => (item.createdDate = null));
    this.setState({
      attachments: response,
      attachmentChange: true,
      invoiceList,
    });
  };

  /**
   * 图片上传成功
   */
  uploadElectronicSuccess = (response) => {
    this.setState({
      electronicAttachments: response,
      attachmentChange: true,
    });
  };

  handleChangeSwitch = (value, field) => {
    if (field.messageKey === "associate.application.enable") {
      this.setState({
        showAssociateApplication: value,
      });
    } else if (
      field.name === "参与人情况是否与申请单不同" ||
      field.name === "接收人情况是否与申请单不同"
    ) {
      this.setState({
        isShowPlayerList: true,
      });
    }
  };

  updateShowAssiciateApplication = () => {
    this.setState({
      showAssociateApplication: this.getValueByMessageKey(
        this.state.expenseType.fields,
        "associate.application.enable"
      ),
    });
  };

  getValueByMessageKey = (fields, messageKey) => {
    const field = fields.find((item) => item.messageKey === messageKey);
    if (!field) return null;
    const { form } = this.props;
    const value = form.getFieldValue(field.fieldOID);
    return value;
  };

  /**
   * 币种改变时设置币种
   * @param value
   */
  handleChangeCurrency = (value) => {
    if (value) {
      let nowCurrency = this.getCurrencyFromList(value);
      this.setState({
        invoiceCurrencyCodePrecision: queryCurrencyPrecision(value),
      });
      let { setFieldsValue, getFieldValue, getFieldsValue } = this.props.form;
      this.setState({ nowCurrency }, () => {
        const { nowCurrency } = this.state;
        let { nowExpense, nowPage } = this.state;
        setFieldsValue({ actualCurrencyRate: nowCurrency.rate });
        getFieldsValue().hasOwnProperty("amount") &&
          setFieldsValue({
            amount: Number(
              currencyPrecisionCal(value, getFieldValue("amount"))
            ),
          });
        if (nowExpense) {
          this.getExchangeRate(this.props.form.getFieldValue("createdDate"));
          nowExpense.companyCurrencyRate = nowCurrency.rate;
          if (nowPage === "form") {
            nowExpense.originalActualCurrencyRate = nowCurrency.rate;
            nowExpense.actualCurrencyRate = nowCurrency.rate;
          }
        }
      });
    }
  };
  /*费用发生日期改变
   * */
  handleChangeCreatedDate = (value) => {
    this.setState({
      nowDate: moment(value).format("YYYY-MM-DD"),
    });
    value && this.getExchangeRate(value);
  };

  //根据日期获取汇率
  getExchangeRate(momentDate = moment(new Date())) {
    let { nowCurrency, baseCurrency, nowPage, nowExpense } = this.state;
    let isBaseCurrency =
      baseCurrency.currencyCode && nowCurrency.currencyCode
        ? baseCurrency.currencyCode === nowCurrency.currencyCode
        : true;
    !isBaseCurrency &&
      baseService
        .getExchangeRate(
          nowCurrency.currencyCode,
          momentDate.format("YYYY-MM-DD HH:mm:ss")
        )
        .then((res) => {
          nowCurrency.rate = res.data.rate;
          if (nowExpense) {
            this.props.form.setFieldsValue({
              actualCurrencyRate: nowCurrency.rate,
            });
            nowExpense.companyCurrencyRate = nowCurrency.rate;
            if (nowPage === "form") {
              nowExpense.originalActualCurrencyRate = nowCurrency.rate;
              nowExpense.actualCurrencyRate = nowCurrency.rate;
            }
          }
          this.setState({ nowCurrency });
        });
  }

  //财务操作发票（增加、删除、修改）后，需要重新获取费用上的信息
  refreshExpenseInfo = () => {
    let { nowExpense } = this.state;
    this.props.editNowExpenseCallBack(nowExpense).then((res) => {
      nowExpense.invoiceLabels = res.invoiceLabels;
      nowExpense.originalApprovedNonVat = res.originalApprovedNonVat;
      nowExpense.originalApprovedVat = res.originalApprovedVat;
      this.setState({ nowExpense });
    });
  };

  //删除发票
  handleDeleteReceipt = (receipt, index) => {
    let { receiptList } = this.state;
    if (this.getAuditOperateAuth()) {
      receiptList[index].deleteLoading = true;
      this.setState({ receiptList });
      expenseService
        .deleteReceipt(receipt.id)
        .then((res) => {
          receiptList.splice(index, 1);
          this.setState({ receiptList }, () => {
            this.getInvoiceTaxAmount();
            this.setAmountByReceipt(receiptList, "delete");
          });
          this.refreshExpenseInfo();
          message.success(messages("my-account.key160") /*删除成功*/);
        })
        .catch((e) => {
          receiptList[index].deleteLoading = false;
          this.setState({ receiptList });
          errorMessage(e.response);
        });
    } else {
      receiptList.splice(index, 1);
      this.setState({ receiptList }, () => {
        this.getInvoiceTaxAmount();
        this.setAmountByReceipt(receiptList, "delete");
      });
    }
  };

  //操作场景初始化
  receiptOperateSceneInit = (type, receipt = null, receiptIndex = 0) => {
    if (type === 2) {
      let { receiptList } = this.state;
      let amount = this.getExpenseItemValue("amount") || 0;
      receipt = {};
      if (receiptList && receiptList.length > 0) {
        let receiptAllAmount = 0;
        receiptList.map((item) => {
          receiptAllAmount = addCalculate(
            receiptAllAmount,
            item.fee + (item.nonDeductibleAmount || 0)
          );
        });
        if (amount && amount * 100 > receiptAllAmount) {
          receipt.tmpFee = subCalculate(amount * 100, receiptAllAmount);
        }
      } else {
        receipt.tmpFee = amount * 100;
      }
    }
    if (type === 3) {
      this.setState({ receiptIndex });
    }
    this.setState({
      receiptOperateScene: type,
      typeSource: "invoice",
      receipt,
      nowPage: "type",
    });
  };

  //费用类型改变对发票的影响
  handleReceiptByExpenseTypeChangeAsync = (expenseType) => {
    var p = new Promise((resolve, reject) => {
      if (!expenseType || !expenseType.id) {
        resolve(true);
        return;
      }
      let type = 0;
      let { receiptList } = this.state;
      if (
        receiptList &&
        receiptList.length > 1 &&
        !expenseType.multipleInvoiceSupported
      ) {
        type = 1;
      }
      if (
        receiptList &&
        receiptList.length > 0 &&
        !expenseType.pasteInvoiceNeeded
      ) {
        type = 2;
      }
      if (type > 0) {
        let title = 0;
        switch (type) {
          case 1:
            title = messages(
              "my-account.key165"
            ) /*此费用类型只能关联一张发票，切换后只能保留首张发票，确认切换？*/;
            break;
          case 2:
            title = messages(
              "my-account.key166"
            ) /*此费用类型无需关联发票，切换后自动删除发票，确认切换?*/;
            break;
          default:
            break;
        }
        let _this = this;
        //弹框确认
        confirm({
          title: title,
          content: "",
          onOk() {
            switch (type) {
              case 1:
                _this.setState({ receiptList: [receiptList[0]] });
                break;
              case 2:
                _this.setState({ receiptList: [] });
                break;
              default:
                break;
            }
            resolve(true);
          },
          onCancel() {
            resolve(false);
          },
        });
      } else {
        resolve(true);
      }
    });
    return p;
  };

  //获取费用实体信息
  getExpenseItemValue = (itemName) => {
    let { getFieldsValue, getFieldValue } = this.props.form;
    let { nowExpense } = this.state;
    let { readOnly } = this.props;
    if (!readOnly && getFieldsValue().hasOwnProperty(itemName)) {
      return getFieldValue(itemName);
    }
    if (nowExpense) {
      return nowExpense[itemName];
    }
    return null;
  };

  //根据发票列表重置金额
  setAmountByReceipt = (receiptList = [], operation) => {
    const {
      form: { setFieldsValue, getFieldValue, getFieldsValue },
      isAuditEditable,
      expenseReportInfo = {},
    } = this.props;
    const { expenseType, nowExpense, expenseApportion, readOnly } = this.state;
    const apportionEnable =
      readOnly && !isAuditEditable
        ? nowExpense.apportionUsed
        : expenseType.erApportionEnabled;
    let receiptCurrencyIsSame = true;
    let receiptCurrencyIsSameWithExpense = true;
    for (let i = 0; i < receiptList.length - 1; i++) {
      if (
        receiptList[i].vatInvoiceCurrencyCode !==
        receiptList[i + 1].vatInvoiceCurrencyCode
      ) {
        receiptCurrencyIsSame = false;
      }
    }
    if (
      getFieldsValue().hasOwnProperty("invoiceCurrencyCode") &&
      getFieldValue("invoiceCurrencyCode") &&
      receiptList[0] &&
      receiptList[0].vatInvoiceCurrencyCode !==
        getFieldValue("invoiceCurrencyCode")
    ) {
      receiptCurrencyIsSameWithExpense = false;
    }
    //第三方费用 或 报销单只读时 或 差补费用 或扬招 或发票币种不一致 或发票币种与费用币种不一致，更改发票费用金额不变
    if (
      receiptList.length === 0 ||
      expenseType.readonly ||
      this.props.params.readOnly ||
      nowExpense.expenseTypeSubsidyType === 1 ||
      expenseType.messageKey === "yangzhao" ||
      !receiptCurrencyIsSame ||
      !receiptCurrencyIsSameWithExpense
    ) {
      return;
    }
    let currencyCode =
      (getFieldsValue().hasOwnProperty("invoiceCurrencyCode") &&
        getFieldValue("invoiceCurrencyCode")) ||
      this.getCompanyInfo(this.props).baseCurrency;
    let params = {
      receiptViewDTOList: receiptList,
      currencyRate: getFieldValue("actualCurrencyRate") || 1,
      currencyCode,
    };
    this.setState({ loading: true });
    expenseService.getReceiptTotalAmount(params).then((res) => {
      this.getInvoiceTaxAmount();
      this.setState({ loading: false });
      let amount = res.data.rows.totalAmount - 0;
      this.setState({amountValue: amount})
      console.log('this.state.expenseType', this.state.expenseType);
      const { expenseType } = this.state;
      this.handleChangeAmount(amount, expenseType.fields)
      if (getFieldValue("amount") !== amount) {
        if (!this.state.officeCardShow) {
          setFieldsValue({ amount });
          let messageToast = messages("expense-1.key284", {
            arg1: currencyCode,
            arg2: formatNumber(amount),
          }); /*已将费用金额更新为 {arg1} {arg2}*/
          if (operation === "delete") {
            messageToast =
              expenseReportInfo.expenseReportOID &&
              (apportionEnable ||
                expenseApportion.some(
                  (item) => item.applicationApportionmentId
                ))
                ? messages("expense-1.key285") /*费用及分摊金额已更新*/
                : messages("expense-1.key286") /*费用金额已更新*/;
          }
          this.setState({
            isThan5000: amount > 5000 ? false : true,
          });
          message.success(messageToast);
        }
      }
    });
  };

  //操作发票回调
  operateReceiptCallback = (receipt, showOCRFlag) => {
    let { setFieldsValue } = this.props.form;
    let { receiptOperateScene, receiptList, expenseType } = this.state;
    this.setState({ showOCRFlag });
    //费用金额处理
    //fix bug 26710 除了直接查验需要代入费用金额外，费用中添加发票后，费用金额不需要代入发票金额
    if (receiptOperateScene === 1 && receiptList.length === 0) {
      let thirdInvoice = !this.props.readOnly && expenseType.readonly;
      if (receipt.fee && !thirdInvoice) {
        //fix bug 24556 第三方费用-录入发票-不需要代入发票的价税合计
        setFieldsValue({
          amount:
            receipt.fee / 100 +
            (receipt.nonDeductibleAmount
              ? receipt.nonDeductibleAmount / 100
              : 0),
        });
      }
    }
    //发票操作场景处理,创建，或者新增
    if (receiptOperateScene === 1 || receiptOperateScene === 2) {
      receiptList.push(receipt);
      this.setState({ receipt, receiptList }, () => {
        this.getDefaultValueByInvoice();
        receiptOperateScene === 2 && this.setAmountByReceipt(receiptList);
      });
    }
    //修改发票信息
    if (receiptOperateScene === 3) {
      console.log('11111, 0');
      let { receiptIndex } = this.state;
      receiptList[receiptIndex] = receipt;
      this.setState({ receiptList }, () => {
        this.getDefaultValueByInvoice();
        this.setAmountByReceipt(receiptList);
      });
    }
    let receiptDate = undefined,
      configResults = [];
    receiptList.map((receiptItem) => {
      if (
        receiptItem.billingTime &&
        (!receiptDate || receiptItem.billingTime < receiptDate)
      ) {
        receiptDate = receiptItem.billingTime;
      }
      if (receiptItem.configResultDTO) {
        configResults.push(receiptItem.configResultDTO);
      }
    });
    if (receiptOperateScene === 1) {
      // 1.发票创建费用
      let createdDate = receiptDate
        ? moment(new Date(receiptDate * 1000))
        : expenseType.occurDateDefaultValue === "CURRENT"
        ? moment(new Date())
        : undefined;
      setFieldsValue({ createdDate });
    }
    //财务操作发票
    if (this.getAuditOperateAuth()) {
      this.refreshExpenseInfo();
    }
    //获取推荐费用大类
    let taxCodeList = [],
      receipts = [];
    receipt.invoiceGoods &&
      receipt.invoiceGoods.map((item) => {
        item.taxCode && taxCodeList.push(item.taxCode);
      });
    receipts.push({
      receiptTypeNo: receipt.invoiceTypeNo,
      taxCodes: taxCodeList,
    });
    receipts.length > 0
      ? this.getRecommendExpenseTypeList(receipts, configResults)
      : this.setState({ recommendExpenseTypeList: [] });
    // 可分摊金额处理
    this.getInvoiceTaxAmount();
    this.setState({ nowPage: "form", typeSource: "", fromExpense: false });
  };

  //关闭发票操作
  closeReceiptOperate = () => {
    let { receiptOperateScene } = this.state;
    if (receiptOperateScene === 1) {
      this.props.close(true);
    } else {
      this.setState({ nowPage: "form", typeSource: "", fromExpense: false });
    }
  };

  /**
   * 用户选中公务卡明细之后触发
   * @param {*} checkedRecords checkedRecords里包含了一条公务卡数据的所有数据relationMap也是所有的公务卡明细
   * @param {*} result result里面的数据只有id、createDate、relationMap（只有选中的明细）、oriCurCod、posCurCod
   * @param {*} type 单选还是多选single more
   */
  handleSelectBusinessCardConsumptions = (checkedRecords, result, type) => {
    let { businessCardConsumptions, singleBusinessCards } = this.state;
    // console.log('result', result, 'type', type, 'checkedRecords',checkedRecords)
    // baseService.getNewAttExpense(this.state.nowExpense.invoiceOID).then((res)=>{
    //   //暂时没用到
    // })
    if (type === "single") {
      if (result.length === 1) {
        businessCardConsumptions = [result[0]];
      } else {
        businessCardConsumptions = [];
      }
      singleBusinessCards = result.slice(1);
    } else if (type === "more") {
      if (checkedRecords.length > 0) {
        businessCardConsumptions = checkedRecords.map((item) => {
          item.trsDate = moment(item.trsDate).format("YYYY-MM-DD");
          result.some((record) => {
            if (record.id === item.id) {
              item.relationMap = record.relationMap;
            }
            return record.id === item.id;
          });
          item.createDate = item.trsDate;
          return item;
        });
      } else {
        businessCardConsumptions = [];
      }
      // businessCardConsumptions = checkedRecords
      businessCardConsumptions = businessCardConsumptions.sort((a, b) => {
        return (
          new Date(a.trsDate).getTime() +
          a.trxTim -
          (new Date(b.trsDate).getTime() + b.trxTim)
        );
      });
    }
    console.log('this.state.nowExpense',this.state.nowExpense);

    this.setState(
      {
        businessCardConsumptions,
        singleBusinessCards,
        nowPage: "form",
        businessCardType: type,
        typeSource: "",
        fromExpense: false,
      },
      this.setValuesByBusinessCard
    );
  };

  handleCancelBusinessCardConsumptions = () => {
    const { fromExpense } = this.state;
    fromExpense
      ? this.setState({ nowPage: "form", typeSource: "", fromExpense: false })
      : this.onCancel();
  };

  //根据商务卡设置费用属性
  setValuesByBusinessCard = () => {
    const { businessCardConsumptions, expenseType } = this.state;
    console.log(`expenseType`, expenseType)
    const companyFlag= businessCardConsumptions.length>0||this.props.type===2||['MCD1028'].includes(expenseType.code)
    const reducer = (accumulator, currentValue) =>
      accumulator + Number(currentValue.posCurAmt);
    if (
      expenseType.readonly &&
      expenseType.messageKey !== "private.car.for.public"
    ) {
      return;
    }
    let arr = businessCardConsumptions.sort((a, b) => {
      return moment(a.createDate) - moment(b.createDate);
    });
    // console.log('businessCardConsumptions', arr)
    if (businessCardConsumptions.length > 0) {
      let target = businessCardConsumptions[0];
      const totalAmount = businessCardConsumptions
        .reduce((pre, now) => {
          if (!now.relationMap) {
            now.relationMap = {};
          }
          const keys = Object.keys(now.relationMap);
          return (
            pre +
            keys.reduce((preKeyAmount, key) => {
              let keyAmount = 0;
              if (now.relationMap[key] && now.relationMap[key].length > 0) {
                const relationArr = deepFullCopy(now.relationMap[key]);
                keyAmount = relationArr.reduce((total, relation) => {
                  if (relation.amount !== 0 && relation.checked) {
                    return relation.amount + total;
                  } else {
                    return total + 0;
                  }
                }, 0);
              }
              return preKeyAmount + keyAmount;
            }, 0)
          );
        }, 0)
        .toFixed(this.getInvoiceCurrencyPrecision());
      const comment = this.props.form.getFieldValue("comment");
      if (this.props.type === 2) {
        this.props.form.setFieldsValue({
          amount: totalAmount,
          invoiceCurrencyCode: target.posCurCod,
          comment: comment + (target.remark || ""),
        });
        this.setState({
          nowExpense: {...this.state.nowExpense, paymentType: '1002'},
        });
      } else {
        this.props.form.setFieldsValue({
          amount: totalAmount,
          invoiceCurrencyCode: target.posCurCod,
          createdDate: moment(target.createDate),
          comment: comment + (target.remark || ""),
        });
        this.setState({
          nowExpense: {...this.state.nowExpense, paymentType: '1002'},
          officeCardShow: true,
        });
      }
      this.handleChangeAmount();
      this.handleChangeCurrency(target.posCurCod);
    } else {
      if (this.props.type === 2) {
        this.props.form.setFieldsValue({
          amount: 0,
        });
      }
    // businessCardConsumptions 为空的时候，说明没有勾选，变为1001（个人支付）
      this.setState({
        nowExpense: {...this.state.nowExpense, paymentType: companyFlag?'1002':'1001'},
        officeCardShow: false,
      });
    }
  };

  getRecommendExpenseTypeList = (receipts, configResults) => {
    let expenseReportInfo = this.props.expenseReport || {};
    let applicationOID = expenseReportInfo.applicationOID || null;
    let expenseReportOID = expenseReportInfo.expenseReportOID || null;
    let formOID = null;
    baseService
      .getRecommendExpenseTypeList(
        receipts,
        applicationOID,
        expenseReportOID,
        formOID,
        configResults
      )
      .then((res) => {
        this.setState({ recommendExpenseTypeList: res.data });
      });
  };

  renderExpenseSourceArea = () => {
    const {
      typeSource,
      currencyList,
      expenseType,
      nowExpense,
      recommendExpenseTypeList,
      invoiceFp,
      receipt,
      receiptList,
      receiptOperateScene,
      receiptIndex,
      OCRList,
      businessCardConsumptions,
      singleBusinessCards,
      isBusinessCardMore,
      isDiDiChange,
      didiOrderId,
    } = this.state;
    let expenseReport = this.props.expenseReport;
    let param;
    if (expenseReport) {
      param = {
        setOfBooksId: expenseReport.setOfBooksId,
        expenseReportOID: expenseReport.expenseReportOID,
        userOID:
          (nowExpense && nowExpense.owner && nowExpense.owner.userOID) ||
          this.props.agentOid ||
          this.props.user.userOID,
        createManually: true,
      };
    } else {
      param = {
        userOID:
          (nowExpense && nowExpense.owner && nowExpense.owner.userOID) ||
          this.props.agentOid ||
          this.props.user.userOID,
      };
    }
    let { profile, pageFrom } = this.props;
    let invoiceUserFp = invoiceFp ? invoiceFp : profile;
    if (this.props.applicant && this.props.applicant.userOID) {
      // 报销单详情里的新建费用抽屉，userOID应该为报销单的申请人，因为有代提的情况所以要单独赋值
      param.userOID = this.props.applicant.userOID;
    }
    switch (typeSource) {
      case "expenseType":
        if (this.props.officialCard && this.props.total <= 0) {
          return (
            <ExpenseTypeSelector
              key="expense-type-selector-plus"
              filter={(item) => item.code === "MCD1196"}
              onSelect={this.handleSelectExpenseType}
              source="custom"
              receiptList={receiptList}
              value={expenseType}
              recommendExpenseTypeList={recommendExpenseTypeList}
              param={param}
              showMessageInfo
            />
          );
        }
        //公务卡生成费用剔除公务卡调整
        if (this.props.officialCard && this.props.total > 0) {
          return (
            <ExpenseTypeSelector
              key="expense-type-selector-plus"
              onSelect={this.handleSelectExpenseType}
              source="custom"
              receiptList={receiptList}
              value={expenseType}
              recommendExpenseTypeList={recommendExpenseTypeList}
              param={param}
              showMessageInfo
            />
          );
        }
        return (
          <ExpenseTypeSelector
            key="expense-type-selector-negative"
            filter={(item) => {
              if (isDiDiChange || this.props.isDiDi) {
                return [
                  "MCD1198",
                  "MCD1199",
                  "MCD1200",
                  "MCD1201",
                  "MCD1202",
                  "MCD1203",
                  "MCD1204",
                  "MCD1205",
                  "MCD1206",
                  "MCD1230",
                  "MCD1231",
                  "MCD1232",
                  "MCD1235",
                  "MCD1418",
                  "MCD1419",
                ].includes(item.code);
              } else {
                return ![
                  // "MCD1199",
                  // "MCD1198",
                  // "MCD1200",
                  // "MCD1201",
                  // "MCD1202",
                  // "MCD1203",
                  // "MCD1204",
                  // "MCD1205",
                  // "MCD1206",
                  // "MCD1230",
                  // "MCD1231",
                  // "MCD1232",
                  // "MCD1235",
                  // "MCD1418",
                  // "MCD1419",
                ].includes(item.code);
              }
            }}
            onSelect={this.handleSelectExpenseType}
            source="custom"
            receiptList={receiptList}
            value={expenseType}
            recommendExpenseTypeList={recommendExpenseTypeList}
            param={param}
            showMessageInfo
          />
        );
      case "invoice":
        let currency = undefined;
        if (
          receipt &&
          currencyList &&
          currencyList.some(
            (item) => item.currency === receipt.vatInvoiceCurrencyCode
          )
        ) {
          currency = receipt.vatInvoiceCurrencyCode;
        }
        return (
          <CreateInvoice
            onCreate={this.operateReceiptCallback}
            currencyList={currencyList}
            createType={this.getAuditOperateAuth() ? 2 : 1} //创建类型：1.用户操作类型2.财务操作类型
            invoiceUserFp={invoiceUserFp}
            invoiceOID={nowExpense.invoiceOID}
            userOID={expenseReport ? expenseReport.applicantOID : ""}
            receiptOperateScene={receiptOperateScene}
            receiptList={receiptList}
            onBack={this.closeReceiptOperate}
            //编辑的发票，若未识别到币种或币种未启用，则置空
            currency={
              receipt && receipt.cardsignType
                ? currency
                : receipt.vatInvoiceCurrencyCode ||
                  (this.props.form.getFieldsValue() || {})
                    .invoiceCurrencyCode ||
                  nowExpense.invoiceCurrencyCode
            }
            pageFrom={pageFrom}
            receipt={receipt}
            receiptIndex={receiptIndex}
            id={this.state.expenseType.id}
          />
        );
      case "businessCard":
        return (
          <BusinessCardConsumption
            ownerOID={this.state.ownerOID}
            onSelect={this.handleSelectBusinessCardConsumptions}
            onCancel={this.handleCancelBusinessCardConsumptions}
            isBusinessCardMore={isBusinessCardMore}
            singleBusinessCards={singleBusinessCards}
            businessCardConsumptions={businessCardConsumptions}
            invoiceOID={nowExpense.invoiceOID || "null"}
            actualCurrencyRate={nowExpense.actualCurrencyRate}
            currencyCode={nowExpense.currencyCode}
            isSingle={this.props.type === 2 ? "single" : "more"}
            // isDidi={true}
          />
        );
      case "didiCard":
        return (
          <DidiRecordSelector
            ownerOID={this.state.ownerOID}
            onSelect={this.handleOkDiDiCard}
            onCancel={this.handleCancelDiDiCard}
            didiOrderId={didiOrderId}
          />
        );
      case "invoiceOCR":
        return (
          <InvoiceOCRList
            invoiceList={OCRList || []}
            invoiceUserFp={invoiceUserFp}
            currencyList={currencyList}
            expenseReport={expenseReport}
            nowExpense={nowExpense}
            receiptList={receiptList}
            createType={this.getAuditOperateAuth() ? 2 : 1} //创建类型：1.用户操作类型 2.财务操作类型
            pageFrom={pageFrom}
            handleImport={this.handleOCRImport}
            cancelImport={() => this.setState({ nowPage: "form" })}
          />
        );
      //不可编辑的发票详情
      case "invoiceDisabledEdit":
        return (
          <div>
            <Invoice invoiceList={[receipt]} canExpense={false} />
            <div style={{ textAlign: "center" }}>
              <a
                onClick={() => this.setState({ nowPage: "form" })}
                style={{ fontSize: 16 }}
              >
                <Icon type="left-circle-o" />
                &nbsp;&nbsp;{messages("common.back") /*返回*/}
              </a>
            </div>
          </div>
        );
    }
  };

  //OCR查验成功发票导入到费用中
  handleOCRImport = (invoiceList) => {
    let { receiptList } = this.state;
    receiptList.push(...invoiceList);
    this.setState({ nowPage: "form", receiptList }, () => {
      //财务添加发票后，重新获取下费用的信息
      if (this.getAuditOperateAuth()) {
        this.refreshExpenseInfo();
      } else {
        //非财务添加发票时，需要获取发票默认值
        this.getDefaultValueByInvoice();
        this.setAmountByReceipt(receiptList);
      }
    });
  };

  // 删除商务卡
  /**
   *
   * @param {*} card 一条包含的整个公务卡消费记录的公务卡消费明细数据
   * @param {*} index
   */
  handleDeleteCard = (card, index) => {
    let { businessCardConsumptions, singleBusinessCards } = this.state;
    const deletedResult = businessCardConsumptions
      .map((record) => {
        if (record.id === card.recordId) {
          if (card.status === "WAIT") {
            record.checkedRelation && (record.checkedRelation["WAIT"] = []);
            record.relationMap["WAIT"] = [];
          } else {
            if (record.checkedRelation) {
              const tempCheckedRelation = record.checkedRelation[card.status]
                .map((relation) => {
                  if (card.relationId === relation.id) {
                    return null;
                  } else {
                    return relation;
                  }
                })
                .filter((item) => item);
              record.checkedRelation[card.status] = tempCheckedRelation;
            }
            const tempRelationMap = record.relationMap[card.status].map(
              (relation) => {
                if (card.relationId === relation.id) {
                  relation.checked = false;
                }
                return relation;
              }
            );
            record.relationMap[card.status] = tempRelationMap;
          }
        }
        const keys = Object.keys(record.relationMap);
        let checkedRelationsNum = 0;
        keys.map((key) => {
          (record.relationMap[key] || []).map((relation) => {
            relation.checked && checkedRelationsNum++;
          });
        });
        if (checkedRelationsNum === 0) {
          return null;
        }
        return record;
      })
      .filter((item) => item);
    // businessCardConsumptions.splice(index, 1);
    // if (!businessCardConsumptions[0] && singleBusinessCards.length > 0) {
    //   businessCardConsumptions = [singleBusinessCards[0]];
    //   singleBusinessCards.splice(0, 1);
    // }
    if (!deletedResult[0] && singleBusinessCards.length > 0) {
      deletedResult = [singleBusinessCards[0]];
      singleBusinessCards.splice(0, 1);
    }
    message.success(messages("common.delete.successful") /*删除成功*/);
    console.log(businessCardConsumptions,'businessCardConsumptions4');
    this.setState({ businessCardConsumptions: deletedResult }, () => {
      // this.forceUpdate()
      // if (!!businessCardConsumptions[0]) {
      this.setValuesByBusinessCard();
      // }
    });
  };

  // 删除滴滴卡片
  /**
   *
   * @param {*} card
   * @param {*} index
   */
  handleDeleteCards = (card, index) => {
    let { didiArr, singleBusinessCards } = this.state;
    const { expenseType,lastExpenseDetail} = this.state;
    const { form } = this.props;
    let ExpenseDetail = deepCopy(lastExpenseDetail)

    console.log(card,'card');
    console.log(didiArr,'didiArr');

    let deletedResult = didiArr
      .filter((record) => {
        if (record.id !== card.id) {
           return record
        }
      })
    console.log(deletedResult, 'deletedResult');
    ExpenseDetail.fields = expenseType.fields.map((item) => {
      let fieldOID = item.fieldOID;
      let obj = {};
      if (deletedResult.length === 0) {
        switch (item.messageKey) {
          case "helios.location":
            obj = {};
            obj[fieldOID] = '';
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;

          case "helios.departure.location":
            obj = {};
            obj[fieldOID] = '';
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          case "helios.destination.location":
            obj = {};
            obj[fieldOID] = '';
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;

          case "total.amount":
            obj = {};
            obj[fieldOID] = 0;
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          default:
            break;
        }
        form.setFieldsValue({
          amount: 0,
          createdDate:null,
        })
        this.setState({
          didiRelationAmount: 0,
        })
      }
      if (deletedResult.length === 1) {
        switch (item.messageKey) {
          case "helios.location":
            obj = {};
            obj[fieldOID] = deletedResult[0].cityName;
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;

          case "helios.departure.location":
            obj = {};
            obj[fieldOID] = deletedResult[0].actualStartName;
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          case "helios.destination.location":
            obj = {};
            obj[fieldOID] = deletedResult[0].actualEndName;
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;

          case "total.amount":
            obj = {};
            obj[fieldOID] = deletedResult[0].companyRealPay;
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          default:
            break;
        }
        form.setFieldsValue({
          amount: deletedResult[0].companyRealPay,
          createdDate: moment(deletedResult[0].createTime),
        })
        this.setState({
          didiRelationAmount: deletedResult[0].companyRealPay,
        })
      }
      if (deletedResult.length > 1) {
        let total = 0;
        deletedResult.forEach(i => {
          total += i.companyRealPay
        })
        switch (item.messageKey) {
          case "helios.location":
            obj = {};
            obj[fieldOID] = '';
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;

          case "helios.departure.location":
            obj = {};
            obj[fieldOID] = '';
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          case "helios.destination.location":
            obj = {};
            obj[fieldOID] = '';
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;

          case "total.amount":
            obj = {};
            obj[fieldOID] = 0;
            form.setFieldsValue(obj);
            item.value = obj[fieldOID]
            break;
          default:
            break;
        }
        form.setFieldsValue({
          amount: total,
        })
        this.setState({
          didiRelationAmount: total,
        })
      }
      return item;
    });

    message.success(messages("common.delete.successful") /*删除成功*/);
    this.setState({
      didiArr: deletedResult,
    })
  };
  /**
   * 表单控件默认值
   * @param type  field类型
   * @param value  field值
   * @param name  field值的对应名称
   * @param field
   */
  getFieldDefaultValue = (type, value, name, field = {}, didiInfoIndex = 0) => {
    console.log('value', value);
    // debugger
    const {
      expenseReport,
      user,
      type: typeProp,
      didiExpenseInfo = [],
      didiOrderKeys = [],
    } = this.props.params;
    const {
      nowExpense,
      nowExpense: { mileageAllowanceExpenseV2DTO },
      lastExpenseDetail
    } = this.state;
    const { form } = this.props;

    const frontLocations = (value) => {
      return value
        ? JSON.stringify({
            latitude: value.lat,
            longitude: value.lng,
            address: value.place,
          })
        : "";
    };
    console.log(this.state.detailArr, 'this.state.detailArr');

     if(this.state.detailArr.data||[].length > 0){
       const didiExpenseInfos = this.state.detailArr.data
       var city = '';
       var departure = '';
       var destination = '';
       didiExpenseInfos.forEach(i => {

         if (i.messageKey === 'helios.location') {
          city =  i.value
         }
         if (i.messageKey === 'helios.departure.location') {
          departure =  i.value
         }
         if (i.messageKey === 'helios.destination.location') {
          destination =  i.value
         }

       })

       if (field.messageKey === "helios.location") {
        return city
      }
      if (field.messageKey === "helios.departure.location") {
       return departure
      }
      if (field.messageKey === "helios.destination.location") {
       return destination
       }

    }


    // 新增的电子支付金额默认为上方填写的金额 ，可编辑
    if (field.messageKey === "dianzizhif") {
      if(!field.value){
        return this.state.amountValue;
      }else{
        return value;
      }
    }

    // 新增wu电子支付金额默认为上方填写的金额 ，bu可编辑
    if (field.messageKey === "wudianzizhif" && !field.value) {
      return 0;
      // if(!field.value){
      //   return this.state.amountValue;
      // }else{
      //   return value;
      // }
    }


    console.log(didiExpenseInfo[didiInfoIndex],'didiExpenseInfo[didiInfoIndex]');
    console.log(this.props,'this.props');


    // 返回滴滴费用的value(只用于滴滴打车消费生成费用页面)
    if (typeProp && typeProp === 2 && didiExpenseInfo.length > 0) {
      console.log(2222)
      if (field.messageKey === "vehicle.type") {
        // 用车方式 2:专车，3:快车，5:豪华车
        const vehicleType = {
          2: "专车",
          3: "快车",
          5: "豪华车",
        };
        return didiExpenseInfo[didiInfoIndex].useCarType
          ? vehicleType[didiExpenseInfo[didiInfoIndex].useCarType]
          : null;
      }
      if (field.messageKey === "order.amount") {
        // 订单金额 订单金额=个人支付金额+优惠券
        return String(didiExpenseInfo[didiInfoIndex].personalPay || 0);
      }
      if (field.messageKey === "order.currencyCode") {
        // 订单币种
        return "CNY";
      }
      if (field.messageKey === "require.level") {
        // 车型 100: '舒适型', 400: '商务型', 200: '豪华型', 500: '优选型', 600: '快车', 900: '优享型'
        const carType = {
          100: "舒适型",
          400: "商务型",
          200: "豪华型",
          500: "优选型",
          600: "快车",
          900: "优享型",
        };
        return didiExpenseInfo[didiInfoIndex].requireLevel &&
          didiExpenseInfo[didiInfoIndex].requireLevel.length > 0
          ? carType[didiExpenseInfo[didiInfoIndex].requireLevel]
          : null;
      }
      if (field.messageKey === "company.real.pay") {
        // 公司支付
        return (
          didiExpenseInfo[didiInfoIndex].companyPay &&
          String(didiExpenseInfo[didiInfoIndex].companyPay)
        );
      }
      if (field.messageKey === "personal.real.pay") {
        // 个人支付
        return (
          didiExpenseInfo[didiInfoIndex].personalPay &&
          String(didiExpenseInfo[didiInfoIndex].personalPay)
        );
      }
      if (field.messageKey === "coupon.amount") {
        // 优惠券抵扣
        return (
          didiExpenseInfo[didiInfoIndex].voucherPay &&
          String(didiExpenseInfo[didiInfoIndex].voucherPay)
        );
      }
      if (field.messageKey === "total.amount") {
        // 总金额
        return (
          didiExpenseInfo[didiInfoIndex].totalPrice &&
          String(didiExpenseInfo[didiInfoIndex].totalPrice)
        );
      }
      if (field.messageKey === "normal.distance") {
        // 总里程
        return (
          didiExpenseInfo[didiInfoIndex].normalDistance &&
          String(didiExpenseInfo[didiInfoIndex].normalDistance)
        );
      }
      if (didiExpenseInfo.length > 1) {
        if (field.messageKey === "helios.location") {
          // 城市
          return '';
        }
        if (field.messageKey === "helios.departure.location") {
          // 出发地
          return '';
        }
        if (field.messageKey === "helios.destination.location") {
          // 目的地
          return '';
        }
      } else {
        if (field.messageKey === "helios.location") {
          // 城市
          return didiExpenseInfo[didiInfoIndex].cityName;
        }
        if (field.messageKey === "helios.departure.location") {
          // 出发地
          return didiExpenseInfo[didiInfoIndex].actualStartName;
        }
        if (field.messageKey === "helios.destination.location") {
          // 目的地
          return didiExpenseInfo[didiInfoIndex].actualEndName;
        }
      }

      if (field.messageKey === "helios.start.time") {
        // 出发时间
        return didiExpenseInfo[didiInfoIndex].departureTime
          ? moment(didiExpenseInfo[didiInfoIndex].departureTime).format(
              "YYYY-MM-DD HH:mm:ss"
            )
          : null;
      }
      if (field.messageKey === "helios.end.time") {
        // 到达时间
        return didiExpenseInfo[didiInfoIndex].finishTime
          ? moment(didiExpenseInfo[didiInfoIndex].finishTime).format(
              "YYYY-MM-DD HH:mm:ss"
            )
          : null;
      }
      if (field.messageKey === "associate.application") {
        // 预定及申请
        return didiExpenseInfo[didiInfoIndex].outApprovalId;
      }
      if (field.messageKey === "dateCombined") {
        // 差旅日期,不需要在滴滴详情里查出来，用户手动输入之后存入费用里
        return null;
      }
      return null;
    }
    if (field.messageKey === "vehicle.type") {
      // 用车方式 2:专车，3:快车，5:豪华车
      const vehicleType = {
        2: "专车",
        3: "快车",
        5: "豪华车",
      };
      return vehicleType[value];
    }
    if (field.messageKey === "require.level") {
      // 车型 100: '舒适型', 400: '商务型', 200: '豪华型', 500: '优选型', 600: '快车', 900: '优享型'
      const carType = {
        100: "舒适型",
        400: "商务型",
        200: "豪华型",
        500: "优选型",
        600: "快车",
        900: "优享型",
      };
      return carType[value];
    }
    //后端自定义字段日期，UTC是假的UTC,显示的时候特殊处理（修改了保存的时间格式，现在是真的utc时间，不需要特殊处理）
    if (
      value &&
      ((field && field.messageKey === "dateCombined") ||
        type === "START_DATE_AND_END_DATE")
    ) {
      return value;
    }
    if (type === "DATETIME" || type === "DATE") {
      if (mileageAllowanceExpenseV2DTO) {
        if (field.messageKey === "arrive.time") {
          return moment(
            mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].arriveTime
          );
        }

        if (field.messageKey === "depart.time") {
          return moment(
            mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].departTime
          );
        }
      }
      return value ? moment(value) : null;
    }
    if (type === "PARTICIPANTS") {
      if (this.props.type === 3) {
        const expenseReport = this.props.params.expenseReport || {};
        // 代第三方报销单，参与人信息自动带出司机的审批人 https://pmo.mcd.com.cn/jira/browse/TES-2186
        if (expenseReport.formCode === "BX006") {
          const carPersonInfo = expenseReport.carPerson || {};
          if (carPersonInfo.approvalOID) {
            return [
              {
                userOID: expenseReport.carPerson.approvalOID,
                fullName: expenseReport.carPerson.approvalName,
              },
            ];
          }
          return [];
        }
        // 代他人报销单自动带出被代理人作为参与人信息 https://pmo.mcd.com.cn/jira/browse/TES-2186
        const { applicant } = this.props;
        if (applicant.userOID !== this.props.user) {
          // 默认有值的时候取值 https://pmo.mcd.com.cn/jira/browse/TES-2301
          return value
            ? JSON.parse(value)
            : [{ userOID: applicant.userOID, fullName: applicant.fullName }];
        }
      }
      console.log("value", value, this.props.user);
      return value
        ? JSON.parse(value)
        : nowExpense.id || (expenseReport || {}).expenseReportOID
        ? undefined
        : this.props.agentOid
        ? [{ userOID: this.props.agentOid, fullName: this.props.agentName }]
        : [{ userOID: user.userOID, fullName: user.fullName }];
    }
    if (type === "PARTICIPANT") {
      if (value) {
        let participant = JSON.parse(value);
        if (participant.userOID) {
          return [{ fullName: name, userOID: participant.userOID }];
        } else {
          return [];
        }
      } else {
        return [];
      }
    }
    if (type === "LOCATION") {
      return value ? { label: name, key: value } : null;
    }
    if (type === "MONTH") {
      if (nowExpense.invoiceOID) {
        return value ? moment(value) : null;
      } else {
        return value ? moment(value) : moment(new Date());
      }
    }
    if (type === "CUSTOM_ENUMERATION") {
      if (field.customEnumerationOID && field.value && field.value !== "") {
        value = [
          {
            value: field.value,
            messageKey: field.showValue,
          },
        ];
        return value;
      } else if (value) {
        return [
          {
            value,
            messageKey: name,
          },
        ];
      } else {
        return undefined;
      }
    }
    if (type === "COMPANY_PAID") {
      //公司已付
      return value ? value === "1002" : field.defaultValueKey === "1002";
    }
    if (type === "BOOLEAN") {
      //普通开关
      return value === "true";
    }
    if (type === "ASSOCIATE_APPLICATION") {
      //关联申请单
      return value ? [{ businessCode: value }] : undefined;
    }

    if (mileageAllowanceExpenseV2DTO) {
      if (field.messageKey === "depart.place") {
        const value =
          mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].start;
        return frontLocations(value);
      }

      if (field.messageKey === "destination") {
        const value =
          mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].end;
        return frontLocations(value);
      }

      if (field.messageKey === "destination.original") {
        const value =
          mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].originEnd;
        return frontLocations(value);
      }

      if (field.messageKey === "depart.place.original") {
        const value =
          mileageAllowanceExpenseV2DTO.mileageAllowanceOrders[0].originStart;
        return frontLocations(value);
      }
    }

    if (type !== "TEXT" || (!field && type === "TEXT")) {
      return value;
    } else {
      if (field.messageKey === "mcd.car") {
        if (field.value === null) {
          return [];
        }
        value = [
          {
            id: field.fieldOID,
            carNumber: JSON.parse(field.value)[0].carNumber,
          },
        ];
        return value;
      }
      if (field) {
        if (field.customEnumerationOID && field.value && field.value !== "") {
          value = [
            {
              value: field.value,
              messageKey: field.showValue,
            },
          ];
          return value;
        } else {
          // console.log('value', name, field)
          if (field.name === "参与人情况是否与申请单不同") {
            console.log("value", value);
            return value ? value : JSON.stringify([]);
          } else if (field.messageKey === "prompt.key") {
            return String(this.state.unitPrice);
          } else {
            return value;
          }
        }
      } else {
        return value;
      }
    }
  };

  //费用分摊变化时
  handleChangeExpenseApportion = (expenseApportion) => {
    this.setState({ expenseApportion });
  };

  isAllowedFile = (file) => {
    let sections = (file.response
      ? file.response.fileName
      : file.fileName
    ).split(".");
    let extension = sections[sections.length - 1].toLowerCase();
    let allowedSuffix = [
      "png",
      "gif",
      "jpg",
      "jpeg",
      "bmp",
      "doc",
      "docx",
      "ppt",
      "pptx",
      "xls",
      "xlsx",
      "txt",
      "pdf",
    ];
    return allowedSuffix.has(extension);
  };

  handlePreviewFile = (attachment) => {
    if (this.isAllowedFile(attachment)) {
      this.setState({ showFileAudit: true, defaultAttachment: attachment });
    } else {
      window.open(
        attachment.response ? attachment.response.fileURL : attachment.fileURL,
        "_blank"
      );
    }
  };

  //数据处理，筛选有图片附件的费用
  handleAllowedFileInvoices = (invoices) => {
    let tmpInvoices = deepFullCopy(invoices || []);
    tmpInvoices.map((invoice) => {
      if (invoice.attachments && invoice.attachments.length) {
        invoice.attachments = invoice.attachments.filter((res) =>
          this.isAllowedFile(res)
        );
      }
      return invoice;
    });
    return tmpInvoices;
  };

  handleEditAuditAmount = () => {
    const { nowExpense } = this.state;
    this.setState({ auditAmountEditing: true }, () => {
      this.props.form.setFieldsValue({
        amount: nowExpense.amount,
        actualCurrencyRate: nowExpense.actualCurrencyRate,
        originalApprovedNonVat:
          nowExpense.originalApprovedNonVat != null
            ? nowExpense.originalApprovedNonVat
            : nowExpense.amount,
        originalApprovedVat: nowExpense.originalApprovedVat
          ? nowExpense.originalApprovedVat
          : 0,
      });
    });
  };

  handleSaveAuditAmount = () => {
    const { profile } = this.props;
    const { nowExpense, isNonVat, receiptList } = this.state;
    let amountIsNotChangeBig = !profile["finance.change.big.amount"];
    this.props.form.validateFieldsAndScroll((err, values) => {
      let expenseReport = this.props.expenseReport;
      if (!err) {
        //需求6324，财务录入不受这个fp控制
        // if (!profile['All.FeeAmount.AllowZero'] && values.amount === 0) {
        //   message.error(messages('my-account.key94'/*核定金额不能为0*/));
        //   return;
        // }
        // if (!values.originalApprovedNonVat && isNonVat && !profile['All.FeeAmount.AllowZero']) {
        //   message.error(messages('my-account.key97'/*原币金额不能为空*/));
        //   return;
        // }
        if (amountIsNotChangeBig && values.amount > nowExpense.originalAmount) {
          message.error(
            messages("my-account.key95" /*核定金额不能大于原金额*/)
          );
          return;
        }
        if (
          amountIsNotChangeBig &&
          values.actualCurrencyRate > nowExpense.companyCurrencyRate
        ) {
          message.error(
            messages("my-account.key96" /*核定汇率不能大于原汇率*/)
          );
          return;
        }
        if (values.originalApprovedNonVat && isNonVat) {
          if (values.originalApprovedNonVat > values.amount) {
            message.error(
              messages("my-account.key98" /*原币金额不能大于原金额*/)
            );
            return;
          }
        }
        let priceTaxAmount = 0;
        receiptList &&
          receiptList.length > 0 &&
          receiptList.map((item) => {
            item.fee = item.fee || 0;
            priceTaxAmount = addCalculate(
              priceTaxAmount,
              item.fee / 100 +
                (item.nonDeductibleAmount ? item.nonDeductibleAmount / 100 : 0)
            );
          });
        let invoiceControl =
          profile["InvoiceControl.InvoiceAmount.FeeAmount.ALL.Equal"];
        if (invoiceControl === 0 || !invoiceControl) {
          if (
            receiptList &&
            receiptList.length > 0 &&
            Number(values.amount) > priceTaxAmount
          ) {
            message.error(
              messages(
                "my-account.key78" /*费用金额必须小于等于发票的价税合计*/
              )
            );
            return;
          }
        } else if (invoiceControl === 2 || invoiceControl === true) {
          if (
            receiptList &&
            receiptList.length > 0 &&
            Number(values.amount) !== priceTaxAmount
          ) {
            message.error(
              messages("my-account.key79" /*费用金额必须等于发票的价税合计*/)
            );
            return;
          }
        }
        let params = {
          actualCurrencyRate:
            values.actualCurrencyRate || nowExpense.actualCurrencyRate,
          amount: values.amount,
          originalApprovedNonVat: values.originalApprovedNonVat,
          originalApprovedVat: values.originalApprovedVat,
          originalActualCurrencyRate: nowExpense.originalActualCurrencyRate,
          originalAmount: nowExpense.originalAmount,
          invoiceOID: nowExpense.invoiceOID,
          expenseReportOID: expenseReport.expenseReportOID,
        };
        this.setState({ savingAuditAmount: true });
        expenseService
          .editAuditAmount(params)
          .then((res) => {
            this.setState(
              {
                savingAuditAmount: false,
                auditAmountEditing: false,
              },
              () => this.onCancel(true)
            );
            message.success(messages("common.operate.success"));
          })
          .catch((e) => {
            errorMessage(e.response);
            this.setState({ savingAuditAmount: false });
          });
      }
    });
  };

  handleToTalMoneyChange = (e) => {
    const {
      nowExpense,
      isNonVat,
      receiptList,
      weatherChangeOriginalApprovedNonVat,
      expenseType,
    } = this.state;
    if (isNonVat) {
      if (!e) {
        this.props.form.setFieldsValue({
          originalApprovedVat: currencyPrecisionCal(nowExpense.invoiceCode, 0),
          originalApprovedNonVat: currencyPrecisionCal(
            nowExpense.invoiceCode,
            0
          ),
        });
        return -1;
      }
      let temp = {
        receiptList,
        currencyPrecision: queryCurrencyPrecision(nowExpense.invoiceCode),
        amount: e,
        originalAmount: nowExpense.originalAmount,
        expenseTypeId: expenseType.id,
        withReceipt: expenseType.pasteInvoiceNeeded,
      };
      let value = Number(
        this.props.form.getFieldValue("originalApprovedNonVat")
      );
      weatherChangeOriginalApprovedNonVat &&
        (temp.originalApprovedNonVat = value);
      expenseService
        .getOriginalApprovedVat(temp)
        .then((res) => {
          this.props.form.setFieldsValue({
            originalApprovedVat: res.data.rows.originalApprovedVat,
            originalApprovedNonVat: res.data.rows.originalApprovedNonVat,
          });
        })
        .catch((e) => {
          errorMessage(e.response);
        });
    }
    this.reRender();
  };

  weatherChange = () => {
    const { blurOriginalApprovedNonVat } = this.state;
    let value = Number(this.props.form.getFieldValue("originalApprovedNonVat"));
    value !== blurOriginalApprovedNonVat &&
      this.setState({ weatherChangeOriginalApprovedNonVat: true });
  };

  blurSetValue = () => {
    let value = Number(this.props.form.getFieldValue("originalApprovedNonVat"));
    this.setState({ blurOriginalApprovedNonVat: value });
  };

  // 标签显示信息
  showMessage = (item) => {
    if (!item.name) {
      return item.toast;
    }
    if (!item.toast) {
      return item.name;
    }
    return `${item.name} : ${item.toast}`;
  };

  changeOriginalApprovedNonVat = (e) => {
    const { nowExpense } = this.state;
    if (typeof e === "number") {
      //需求6324，财务录入不受这个fp控制
      // if (!this.props.profile['All.FeeAmount.AllowZero'] && !e) {
      //   message.error(messages('my-account.key101'/*请输入原币金额*/));
      //   this.props.form.setFieldsValue({originalApprovedVat: currencyPrecisionCal(nowExpense.currencyCode,0)});
      // }
      // else {
      //   let value = Number(this.props.form.getFieldValue('amount'));
      //   let originalApprovedVat = (value - e).toFixed(queryCurrencyPrecision(nowExpense.currencyCode));
      //   this.props.form.setFieldsValue({originalApprovedVat: originalApprovedVat});
      // }
      let value = Number(this.props.form.getFieldValue("amount"));
      let originalApprovedVat = (value - e).toFixed(
        queryCurrencyPrecision(nowExpense.currencyCode)
      );
      this.props.form.setFieldsValue({
        originalApprovedVat: originalApprovedVat,
      });
    }
  };

  //补贴类型费用计算总金额
  getAmount = (e, isNumber = false) => {
    const { getFieldValue, setFieldsValue } = this.props.form;
    let currencyPrecision = this.getInvoiceCurrencyPrecision();
    let result = 0;
    if (isNumber) {
      if (e >= 0) {
        let unitPrice = Number(getFieldValue("unitPrice"));
        if (unitPrice) {
          result = (Number(e) * unitPrice).toFixed(currencyPrecision);
          setFieldsValue({ amount: result });
        } else {
          setFieldsValue({ amount: 0 });
        }
      } else {
        message.error(messages("my-account.key102" /*请输入数量*/));
      }
    } else {
      if (e >= 0) {
        let number = Number(getFieldValue("number"));
        if (number) {
          result = (Number(e) * number).toFixed(currencyPrecision);
          setFieldsValue({ amount: result });
        } else {
          setFieldsValue({ amount: 0 });
        }
      } else {
        message.error(messages("my-account.key103" /*请输入单价*/));
      }
    }
    this.setState({ isWorthAmount: Number(result) !== 0 });
  };

  //渲染添加发票方式的选项
  renderInvoiceAddMenu = () => {
    const { expenseType, nowExpense } = this.state;
    let handleMenuItemClick = (e) => {
      if (e.key === "hand") {
        this.receiptOperateSceneInit(2);
      }
    };
    let checkOCRSuccess = (OCRList) => {
      this.setState({ OCRList }, () => {
        this.setState({ typeSource: "invoiceOCR", nowPage: "type" });
      });
    };
    let invoiceEdit = (receipt) => {
      this.setState({ receipt, receiptOperateScene: 2 }, () => {
        this.setState({ typeSource: "invoice", nowPage: "type" });
      });
    };
    let importSuccessInvoice = (receipt) => {
      this.setState({ receiptList: [receipt] }, () => {
        //非财务添加发票时，需要获取发票默认值
        if (!this.getAuditOperateAuth()) {
          this.getDefaultValueByInvoice();
          this.setAmountByReceipt([receipt]);
        }
      });
    };
    let toEditDisabledPage = (receipt) => {
      this.setState({ receipt }, () => {
        this.setState({ typeSource: "invoiceDisabledEdit", nowPage: "type" });
      });
    };
    return (
      <Menu onClick={handleMenuItemClick}>
        <Menu.Item key="ocr" style={{ padding: 0 }}>
          <InvoiceOCRCheck
            type="image"
            expenseType={expenseType || {}}
            nowExpense={nowExpense}
            createType={this.getAuditOperateAuth() ? 2 : 1} //创建类型：1.用户操作类型 2.财务操作类型
            checkSuccess={checkOCRSuccess}
            invoiceEdit={invoiceEdit}
            importSuccessInvoice={importSuccessInvoice}
            toEditDisabledPage={toEditDisabledPage}
          />
        </Menu.Item>
        <Menu.Item key="pdf" style={{ padding: 0 }}>
          <InvoiceOCRCheck
            type="pdf"
            expenseType={expenseType || {}}
            nowExpense={nowExpense}
            createType={this.getAuditOperateAuth() ? 2 : 1} //创建类型：1.用户操作类型 2.财务操作类型
            checkSuccess={checkOCRSuccess}
            invoiceEdit={invoiceEdit}
            importSuccessInvoice={importSuccessInvoice}
            toEditDisabledPage={toEditDisabledPage}
          />
        </Menu.Item>
        <Menu.Item key="ofd" style={{ padding: 0 }}>
          <InvoiceOCRCheck
            type="ofd"
            expenseType={expenseType || {}}
            nowExpense={nowExpense}
            createType={this.getAuditOperateAuth() ? 2 : 1} //创建类型：1.用户操作类型 2.财务操作类型
            checkSuccess={checkOCRSuccess}
            invoiceEdit={invoiceEdit}
            importSuccessInvoice={importSuccessInvoice}
            toEditDisabledPage={toEditDisabledPage}
          />
        </Menu.Item>
        <Menu.Item key="hand">
          {messages("my-account.key270") /*手动录入*/}
        </Menu.Item>
      </Menu>
    );
  };

  //渲染【添加发票】按钮
  renderButtonAddInvoice = (receiptList, showOCRFlag) => {
    let onDisabledClick = () =>
      message.warning(
        messages("my-account.key330") /*单个费用最多关联50张发票*/
      );
    return (
      <Condition>
        <If value={showOCRFlag}>
          <Condition>
            <If value={receiptList.length < 50}>
              <Dropdown
                getPopupContainer={() =>
                  document.getElementsByClassName("add-invoice-container")[0]
                }
                overlay={this.renderInvoiceAddMenu()}
              >
                <a>
                  {messages("my-account.key161") /*添加发票*/}{" "}
                  <Icon type="down" />
                </a>
              </Dropdown>
            </If>
            <Else>
              <span className="add-invoice-disabled" onClick={onDisabledClick}>
                {messages("my-account.key161") /*添加发票*/}{" "}
                <Icon type="down" />
              </span>
            </Else>
          </Condition>
        </If>
        <Else>
          <Condition>
            <If value={receiptList.length < 50}>
              <a onClick={() => this.receiptOperateSceneInit(2)}>
                <Icon type="edit" />{" "}
                {messages("my-account.key161") /*添加发票*/}
              </a>
            </If>
            <Else>
              <span className="add-invoice-disabled" onClick={onDisabledClick}>
                <Icon type="edit" />{" "}
                {messages("my-account.key161") /*添加发票*/}
              </span>
            </Else>
          </Condition>
        </Else>
      </Condition>
    );
  };

  renderInvoiceEditingArea = () => {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12, offset: 1 },
    };
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { profile } = this.props;
    const {
      expenseType,
      nowExpense,
      readOnly,
      invoiceFp,
      receiptList,
      showOCRFlag,
      lovEditable,
    } = this.state;
    let invoiceUserFp = invoiceFp ? invoiceFp : profile;
    let pasteInvoiceNeeded = expenseType.pasteInvoiceNeeded;
    let multipleInvoiceSupported = expenseType.multipleInvoiceSupported;
    let thirdWithReceipt = nowExpense.withReceipt;
    let hasInvoiceInstead =
      !profile["invoice.instead.disabled"] &&
      (readOnly ? thirdWithReceipt : pasteInvoiceNeeded);
    let invoiceInsteadText = profile["invoice.instead.comments"]
      ? messages("my-account.key104" /*是否备注*/)
      : messages("my-account.key105" /*是否替票*/);
    let invoiceInsteadReasonText = profile["invoice.instead.comments"]
      ? messages("my-account.key106" /*备注理由*/)
      : messages("my-account.key107" /*替票理由*/);
    let invoiceInstead =
      hasInvoiceInstead &&
      (readOnly && this.props.readOnly
        ? nowExpense.invoiceInstead
        : getFieldValue("invoiceInstead"));
    let isDiDi = expenseType.messageKey === "expense.type.didi";
    const isMile = expenseType.messageKey === "private.car.for.public";
    let thirdEditInvoice =
      !this.props.readOnly &&
      expenseType.readonly &&
      !isDiDi &&
      thirdWithReceipt;
    return (
      <div>
        {hasInvoiceInstead && (
          <FormItem {...formItemLayout} label={invoiceInsteadText}>
            {getFieldDecorator("invoiceInstead", {
              valuePropName: "checked",
              initialValue: false,
            })(
              <Switch
                onChange={(checked) =>
                  !checked &&
                  this.props.form.setFieldsValue({ invoiceInsteadReason: "" })
                }
              />
            )}
          </FormItem>
        )}

        {hasInvoiceInstead && invoiceInstead && (
          <FormItem {...formItemLayout} label={invoiceInsteadReasonText}>
            {getFieldDecorator("invoiceInsteadReason")(
              <Input maxLength="100" disabled={!invoiceInstead} />
            )}
          </FormItem>
        )}

        {pasteInvoiceNeeded &&
          !invoiceUserFp["account.book.VAT.special.invoice.disabled"] && (
            <FormItem
              {...formItemLayout}
              label={messages("my-account.key1") /*录入发票*/}
              required={expenseType.invoiceRequired}
            >
              {multipleInvoiceSupported || receiptList.length < 1 ? (
                <div className="add-invoice-container">
                  {(thirdEditInvoice ||
                    !readOnly ||
                    this.getAuditOperateAuth()) &&
                  (!isMile || (isMile && lovEditable)) ? (
                    this.renderButtonAddInvoice(receiptList, showOCRFlag)
                  ) : (
                    <div>
                      {messages(
                        receiptList.length < 1 ? "common.no" : "common.yes"
                      )}
                    </div>
                  )}
                </div>
              ) : (
                <div>{messages("common.yes")}</div>
              )}
            </FormItem>
          )}
      </div>
    );
  };

  deleteAttachment = (attachmentId) => {
    const { nowExpense, attachments } = this.state;
    //附件必填且是最后一个附件
    let required = this.isRequiredFile();
    if (required && attachments.length === 1) {
      message.error(
        messages(
          "my-account.key108" /*当前页面须至少上传1个附件，请上传其他附件后再删除*/
        )
      );
      return false;
    } else {
      baseService.attachmentDelete(nowExpense.invoiceOID, attachmentId);
      this.setState({ attachmentChange: true });
      return true;
    }
  };

  deleteElectronicAttachment = (attachmentId) => {
    const { nowExpense, electronicAttachments, expenseType } = this.state;
    //附件必填且是最后一个附件 ---废弃了
    let required = this.isRequiredNewFile(expenseType);
    if (required && electronicAttachments.length === 1) {
      message.error(
        messages(
          "my-account.key108" /*当前页面须至少上传1个附件，请上传其他附件后再删除*/
        )
      );
      return false;
    } else {
      baseService.attachmentDelete(nowExpense.invoiceOID, attachmentId);
      this.setState({ attachmentChange: true });
      return true;
    }
  };

  goBottom = (e) => {
    e.preventDefault();
    e.stopPropagation();
    this.refs.expenseFormBox.scrollTop = this.refs.expenseFormBox.scrollHeight;
  };

  getPopupContainer = () => {
    return this.refs.expenseFormBox;
  };
  // 里程补贴渲染
  renderMileageForm = () => {
    const { getFieldDecorator } = this.props.form;
    const { expenseType, readOnly, lovEditable } = this.state;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12, offset: 1 },
    };
    // 参考币种
    let referenceCurrencyFile =
      expenseType.fields.filter(
        (field) => field.messageKey === "reference.currency"
      )[0] || {};
    // 单价 file
    let priceFile =
      expenseType.fields.filter(
        (field) => field.messageKey === "unit.price"
      )[0] || {};
    // 参考单价 file
    let referentPriceFile =
      expenseType.fields.filter(
        (field) => field.messageKey === "reference.price"
      )[0] || {};
    // 参考单价文案 需兼容老数据 不存在参考币种或参考单价值时不显示提示文案
    let currencyValue = this.getFieldDefaultValue(
      referenceCurrencyFile.fieldType,
      referenceCurrencyFile.value,
      referenceCurrencyFile.showValue
    );
    let referentPriceFileValue = this.getFieldDefaultValue(
      referentPriceFile.fieldType,
      referentPriceFile.value,
      referentPriceFile.showValue
    );
    let referentPriceFileText =
      currencyValue && referentPriceFileValue
        ? `${referentPriceFile.name}: ${currencyValue} ${Number(
            referentPriceFileValue
          ).toFixed(2)}`
        : null;
    // 里程 file
    let mileageFile =
      expenseType.fields.filter(
        (field) =>
          field.messageKey === "ER_KM" || field.messageKey === "mileage"
      )[0] || {};
    // 参考里程 file
    let referenceMileageFile =
      expenseType.fields.filter(
        (field) => field.messageKey === "reference.mileage"
      )[0] || {};
    // 参考里程文案 需兼容老数据 不存在参考里程值时不显示提示文案
    let referenceMileageFileValue = this.getFieldDefaultValue(
      referenceMileageFile.fieldType,
      referenceMileageFile.value,
      referenceMileageFile.showValue
    );
    let referenceMileageFileText = referenceMileageFileValue
      ? `${referenceMileageFile.name}: ${
          Math.round(referenceMileageFileValue * 100) / 100
        } KM`
      : null;
    // 单价 里程
    let renderFiles = [
      { ...priceFile, text: referentPriceFileText },
      { ...mileageFile, text: referenceMileageFileText },
    ];

    return readOnly || !lovEditable ? (
      <div>
        {renderFiles.map((renderFile) => (
          <FormItem
            {...formItemLayout}
            label={renderFile.name}
            key={`${renderFile.fieldOID}`}
          >
            <Col span={3}>
              <FormItem style={{ margin: "0" }}>
                {this.getFieldDefaultValue(
                  renderFile.fieldType,
                  renderFile.value,
                  renderFile.showValue,
                  renderFile
                )}
              </FormItem>
            </Col>
            <Col span={1} />
            {renderFile.text && (
              <Col style={{ color: "#D2A98C", fontSize: "12px" }} span={12}>
                {renderFile.text}
              </Col>
            )}
          </FormItem>
        ))}
      </div>
    ) : (
      <div>
        {renderFiles.map((renderFile) => (
          <FormItem
            {...formItemLayout}
            label={renderFile.name}
            key={`${renderFile.fieldOID}`}
          >
            <Col span={10}>
              {(renderFile.name == "参与人清单" ||
                renderFile.name == "接收人清单") &&
              !this.state.isShowPlayerList ? (
                ""
              ) : (
                <FormItem>
                  {getFieldDecorator(`${renderFile.fieldOID}`, {
                    rules: [
                      {
                        required: renderFile.required,
                        message:
                          renderFile.name === "未通过TMC购买国内机票申请"
                            ? "请关联未通过TMC购买国内机票申请"
                            : renderFile.messageKey !== "public.assembly" &&
                              messages("common.name.is.required", {
                                name: renderFile.name,
                              }),
                      },
                      ...this.getFieldRules(renderFile, renderFiles),
                    ],
                    valuePropName: ~["COMPANY_PAID", "BOOLEAN"].indexOf(
                      renderFile.fieldType
                    )
                      ? "checked"
                      : "value",
                    initialValue: this.getFieldDefaultValue(
                      renderFile.fieldType,
                      renderFile.value,
                      renderFile.showValue,
                      renderFile
                    ),
                  })(this.switchField(renderFile))}
                </FormItem>
              )}
            </Col>
            {renderFile.text && (
              <Col span={12} offset={1}>
                <Alert
                  message={renderFile.text}
                  key={renderFile.fieldOID}
                  type={"warning"}
                />
              </Col>
            )}
          </FormItem>
        ))}
      </div>
    );
  };
  //获取汇率容差
  getRateDeviation = () => {
    baseService
      .getRateDeviation(
        this.props.company.tenantId,
        this.props.company.setOfBooksId
      )
      .then((res) => {
        this.setState({
          warnExchangeRateTol: res.data.warnExchangeRateTol,
          prohibitExchangeRateTol: res.data.prohibitExchangeRateTol,
        });
      });
  };

  formItemChange(value) {
    //替票理由控件只有在替票控件打开时显示，set值需要异步set
    if (
      value &&
      Object.prototype.toString.call(value) === "[object Object]" &&
      value["invoiceInstead"]
    ) {
      let { nowExpense } = this.state;
      setTimeout(() => {
        this.props.form.setFieldsValue({
          invoiceInsteadReason: nowExpense.invoiceInsteadReason,
        });
      }, 20);
    }
  }

  //键盘事件,控制费用上一页下一页
  handleKeyUp = (e) => {
    const { nowPage, readOnly, nowExpense, showFileAudit } = this.state;
    const { expenseReport } = this.props;
    if (
      nowPage === "form" &&
      expenseReport &&
      nowExpense.invoiceOID &&
      readOnly &&
      !showFileAudit
    ) {
      switch (e.keyCode) {
        //esc
        case 27: {
          this.onCancel();
          break;
        }
        //⬅
        case 37: {
          this.refs.lastInvoiceButton.handleClick();
          break;
        }
        //⬆
        case 38: {
          this.refs.lastInvoiceButton.handleClick();
          break;
        }
        //➡
        case 39: {
          this.refs.nextInvoiceButton.handleClick();
          break;
        }
        //⬇
        case 40: {
          this.refs.nextInvoiceButton.handleClick();
          break;
        }
      }
    }
  };

  //获取费用操作权限
  getAuditOperateAuth = (textProfile = true) => {
    let { nowExpense } = this.state;
    let {
      auditCapability,
      audit,
      profile,
      expenseReport,
      tab,
      fromBag,
      isWaitForAudit,
    } = this.props;
    console.log("nowExpense", nowExpense);
    console.log("auditCapability", auditCapability);
    return (
      expenseReport &&
      (expenseReport.status === 1002 ||
        expenseReport.status === 1003 ||
        (expenseReport.status === 1010 && textProfile)) && //报销单状态 审批中 或 已通过
      !nowExpense.valid &&
      ((isWaitForAudit &&
        audit &&
        (tab === "prending_audit" || fromBag) &&
        this.checkPageRole("EXPENSEAUDIT", 2) &&
        !(profile["er.disabled"] || profile["finance.audit.disabled"])) ||
        auditCapability)
    );
  };

  //跳转申请单
  skipApplication = (applicationNumber) => {
    baseService
      .queryApplicationInfo(applicationNumber, this.props.company.tenantId)
      .then((res) => {
        if (res.data) {
          let action = "detail";
          let backUrlKey = undefined;
          menuRoute.goForm(this, res.data.formCode, {
            action,
            backUrlKey,
            params: {
              formOID: res.data.formOID,
              applicationOID: res.data.applicationOID,
              id: res.data.id,
            },
            needOpen: true,
          });
        }
        // window.open(menuRoute.getRouteItem('done-approve-request-detail', 'key').url.replace(':formOID', res.data.formOID).replace(':applicationOID', res.data.applicationOID));
      })
      .catch((e) => {
        errorMessage(e.response);
      });
  };

  // 审批中修改文本
  changeFieldValue = (field) => {
    let { nowExpense } = this.state;
    (nowExpense.data || []).map((item) => {
      if (item.fieldOID === field.fieldOID) {
        item.value = field.value;
      }
    });
    this.setState({ nowExpense });
  };
  /**
   *
   * @description 禁用日期
   */
  disabledStartDate = (current) => {
    return current && current > moment().endOf("day");
  };

  //显示说明文字
  handleShowFormDesc = () => {
    const { expenseType } = this.state;
    Modal.info({
      title: expenseType.promptTitle,
      content: expenseType.promptContent,
    });
  };

  // 财务控制能否抵扣
  handleCheckVatInvoice = (checked) => {
    let { nowExpense } = this.state;
    this.setState({ loadingCheck: true });
    expenseService
      .setVatInvoice({ enabled: checked, invoiceOID: nowExpense.invoiceOID })
      .then(() => {
        nowExpense.vatInvoice = checked;
      })
      .catch((err) => {
        errorMessage(err.response);
      })
      .finally(() => {
        this.setState({ loadingCheck: false, nowExpense });
      });
  };

  handleViaPointsValidator = (rule, value, callback) => {
    if (value) {
      value.map((item) => {
        if (
          (!item.arrivalTime && item.place) ||
          (item.arrivalTime && !item.place)
        ) {
          callback(messages("my-account.key331") /*请填写完整*/);
        }
      });
    }
    callback();
  };

  handleViaPoints = (viaPoints) => {
    this.props.form.setFieldsValue({ viaPoints });
  };

  /**
   * 返回非组件元素的tips
   * @param {String} label // 表单元素的label内容
   * @param {String} tips  // label的提示信息内容
   */
  renderTips(label, tips) {
    return (
      <span>
        {label}&nbsp;
        <Tooltip title={tips}>
          <Icon type="question-circle-o" />
        </Tooltip>
      </span>
    );
  }

  hanldeOnViewDetails = (record, index) => {
    let tempRecords = deepFullCopy(this.state.allSelectedRecords);
    if (tempRecords[index].id === record.id) {
      if (
        tempRecords[index].selectedRelationList &&
        tempRecords[index].selectedRelationList.length > 0
      ) {
        tempRecords[index].showDetails = !record.showDetails;
      }
    } else {
      tempRecords.some((item, i) => {
        if (item.id === record.id) {
          if (
            tempRecords[i].selectedRelationList &&
            tempRecords[i].selectedRelationList.length > 0
          ) {
            tempRecords[i].showDetails = !record.showDetails;
            return true;
          }
        }
      });
    }
    this.setState({
      allSelectedRecords: tempRecords,
    });
  };

  /**
   * 格式化数字
   * @param {Number} nStr 数字
   */
  addCommas = (nStr) => {
    nStr = Number(nStr || "0").toFixed(2);
    nStr = nStr + "";
    let x = nStr.split(".");
    let x1 = x[0];
    let x2 = x.length > 1 ? "." + x[1] : "";
    let rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, "$1,$2");
    }
    return x1 + x2;
  };

  changeShareData = (feeAcknowledgers) => {
    // feeAcknowledgers.map(item => {
    //   delete item.precent
    // })
    this.setState({ feeAcknowledgers });
  };

  changePrice = (field, value) => {
    console.log("field", value, field, this.state.expenseType);
    if (this.state.expenseType.code === "MCD1027" && field.name === "公里数") {
      console.log("thos", this.state.expenseType.fields);
      let data = this.state.expenseType.fields.filter(
        (item) => item.name === "总金额"
      );
      let key = data[0].fieldOID;
      console.log("key", this.props.form.getFieldsValue());
      this.props.form.setFieldsValue({
        [key]: Number(value * this.state.unitPrice),
      });
    }
  };

    // 修改可支付金额时更新
  handleChangeInput = (field, value ) => {
    const {expenseType} = this.state;
    console.log("field《《》》", value, field, this.state.expenseType);
    // if(value === undefined){
    //   value = 0;
    // }
    if(field.messageKey === 'dianzizhif'){
      this.changeWuAmount(value, expenseType.fields)
    }
  };

  // 更新无法提供的金额
  changeWuAmount = (value, field) => {
    const {amountValue} = this.state;
    console.log('90890', amountValue, value );
    // 变更wu电子支付金额
    let newValue = value;
    if(field && field.length){
      // let valueNew = 0;
      if(value === undefined){
        newValue = 0;
        setTimeout(()=>{
          field.forEach(item=>{
            if(item.messageKey === 'dianzizhif'){
              let name = item.fieldOID;
              let obj ={};
              obj[name] = 0;
              this.props.form.setFieldsValue(obj)
              // item.value = 0;
            }
          })
        },1000)
      }
      
      field.forEach(item=>{
        if(item.messageKey === 'wudianzizhif'){
          let name = item.fieldOID;
          let value = Number(amountValue) - Number(newValue)
          item.value = value;
          let obj ={};
          obj[name] = value;
          this.props.form.setFieldsValue(obj)
        }
      })
    }

  };

  

  changeSwitch = (data) => {
    this.setState({ feeAcknowledgersIsSwitch: data });
  };

  handleOkDiDiCard = (currentSelectRecord) => {
    const { expenseType,lastExpenseDetail} = this.state;
    const { form } = this.props;
    let didiArr = []
    didiArr = currentSelectRecord
    console.log(didiArr,'didiArr++++');


    let ExpenseDetail = deepCopy(lastExpenseDetail)
    ExpenseDetail.fields = expenseType.fields.map((item) => {
      let fieldOID = item.fieldOID;
      let obj = {};
      console.log(currentSelectRecord,'currentSelectRecord');
      if (currentSelectRecord.length > 0) {
        if (currentSelectRecord.length > 1) {
          currentSelectRecord.forEach(i => {
            switch (item.messageKey) {
              case "require.level":
                obj = {};
                obj[fieldOID] = this.getFieldDefaultValue(
                  item.fieldType,
                  i.requireLevel,
                  i.requireLevel,
                  item
                )
                form.setFieldsValue(obj);
                item.value = i.requireLevel
                break;
              case "helios.location":
                obj = {};
                obj[fieldOID] = '';
                form.setFieldsValue(obj);
                item.value = obj[fieldOID]
                break;

              case "helios.departure.location":
                obj = {};
                obj[fieldOID] = '';
                form.setFieldsValue(obj);
                item.value = obj[fieldOID]
                break;
              case "helios.destination.location":
                obj = {};
                obj[fieldOID] = '';
                form.setFieldsValue(obj);
                item.value = obj[fieldOID]
                break;

              case "helios.start.time":
                let departureTime = moment(i.departureTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                );
                obj = {};
                obj[fieldOID] = departureTime;
                obj.createdDate = moment(i.departureTime);
                item.value = i.departureTime

                form.setFieldsValue(obj);
                break;

              case "helios.end.time":
                let finishTime = moment(i.finishTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                );
                obj = {};
                obj[fieldOID] = finishTime;
                item.value = i.finishTime
                form.setFieldsValue(obj);
                break;

              case "normal.distance":
                obj = {};
                obj[fieldOID] = JSON.stringify(i.normalDistance);
                form.setFieldsValue(obj);
                item.value = obj[fieldOID]
                break;

              case "total.amount":
                obj = {};
                obj[fieldOID] = currentSelectRecord[0].total;
                obj.amount = JSON.stringify(i.companyRealPay);
                obj.amount = currentSelectRecord[0].total
                console.log(obj, '靠我服了');

                form.setFieldsValue(obj);
                item.value = obj[fieldOID]
                break;
              default:
                break;
            }
          })
        } else {

         currentSelectRecord.forEach(i => {
          switch (item.messageKey) {
            case "require.level":
              obj = {};
              obj[fieldOID] = this.getFieldDefaultValue(
                item.fieldType,
                i.requireLevel,
                i.requireLevel,
                item
              )
              form.setFieldsValue(obj);
              item.value = i.requireLevel
              break;
            case "helios.location":
              obj = {};
              obj[fieldOID] = i.cityName;
              form.setFieldsValue(obj);
              item.value = obj[fieldOID]
              break;

            case "helios.departure.location":
              obj = {};
              obj[fieldOID] = i.startName;
              form.setFieldsValue(obj);
              item.value = obj[fieldOID]
              break;
            case "helios.destination.location":
              obj = {};
              obj[fieldOID] = i.endName;
              form.setFieldsValue(obj);
              item.value = obj[fieldOID]
              break;

            case "helios.start.time":
              let departureTime = moment(i.departureTime).format(
                "YYYY-MM-DD HH:mm:ss"
              );
              obj = {};
              obj[fieldOID] = departureTime;
              obj.createdDate = moment(i.departureTime);
              item.value = i.departureTime

              form.setFieldsValue(obj);
              break;

            case "helios.end.time":
              let finishTime = moment(i.finishTime).format(
                "YYYY-MM-DD HH:mm:ss"
              );
              obj = {};
              obj[fieldOID] = finishTime;
              item.value = i.finishTime
              form.setFieldsValue(obj);
              break;

            case "normal.distance":
              obj = {};
              obj[fieldOID] = JSON.stringify(i.normalDistance);
              form.setFieldsValue(obj);
              item.value = obj[fieldOID]
              break;

            case "total.amount":
              obj = {};
              obj[fieldOID] = JSON.stringify(i.companyRealPay);
              obj.amount = JSON.stringify(i.companyRealPay);
              console.log(obj, 'obj');
              // this.state.nowExpense.data[13].value = obj.amount
              // console.log(this.state.nowExpense.data[13].value,'this.state.nowExpense.data[13].value');
              form.setFieldsValue(obj);
              item.value = obj[fieldOID]
              break;
            default:
              break;
          }
        })
        }

     }

      return item;
    });
    this.handleChangeAmount();
    console.log(ExpenseDetail, 'ExpenseDetail');

    this.setState({
      didiArr,
      // didiOrderId: currentSelectRecord.orderId,
      nowPage: "form",
      isRelationDidi: true,
      didiRelationAmount: currentSelectRecord[0].total,
      typeSource: "",
      lastExpenseDetail: ExpenseDetail,

    });
    console.log(this.state.nowExpense,'this.state.nowExpense');
  };
  handleCancelDiDiCard = () => {
    this.setState({ nowPage: "form", typeSource: "" });
  };
  render() {
    const { getAuditOperateAuth } = this;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const {
      profile,
      isWaitForAudit,
      view,
      pay,
      auditCapability,
      jobInfo,
      type,
    } = this.props;
    const {
      nowPage,
      expenseType,
      promptThan300,
      loading,
      saving,
      attachments,
      currencyList,
      nowCurrency,
      baseCurrency,
      nowExpense,
      readOnly,
      pagination,
      subsidyLoading,
      businessCardConsumptions,
      expenseApportion,
      defaultAttachment,
      unitPriceMode,
      mileageMessageKey,
      subsidyData,
      columns,
      auditAmountEditing,
      savingAuditAmount,
      approvalHistory,
      isNonVat,
      invoiceFp,
      prohibitExchangeRateTol,
      warnExchangeRateTol,
      showExpenseDom,
      invoiceCurrencyCodePrecision,
      receiptList,
      expenseLoading,
      actualApportionAmount,
      receiptOperateScene,
      loadingCheck,
      taxRate,
      invoiceList,
      showOCRFlag,
      businessCardType,
      showFileAudit,
      isWorthAmount,
      showExpenseReportInvoices,
      lovEditable,
      allSelectedRecords,
      businessCardEnabledObj,
      officeCardShow,
      isDiDiChange,
      isRelationDidi,
      notShowFileList,
      electronicAttachments,
      amountValue,
    } = this.state;
    let earliestDate = null;
    if (this.props.officialCard) {
      let createDateArr = allSelectedRecords
        .filter(
          (item) =>
            item.selectedRelationList && item.selectedRelationList.length > 0
        )
        .map((item) => moment(item.trsDate || "").valueOf());
      earliestDate = moment(Math.min(...createDateArr));
    }
    let didiAmount = 0;
    if (type === 2) {
      if (this.props.didiExpenseInfo[0]) {
        didiAmount = this.props.didiExpenseInfo[0].companyRealPay || 0;
      }
    }
    //用于始终跟着单据走的FP场景
    let invoiceUserFp = invoiceFp ? invoiceFp : profile;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12, offset: 1 },
    };
    console.log("this.props.agentUser", this.props.agentUser);
    const {
      audit,
      businessCardEnabled,
      costCenterItemsApportion,
      expenseReport,
      user,
      approve,
      isWithTime,
      agentOid,
    } = this.props;
    let userOID = agentOid || user.userOID;
    let expenseUserOID =
      nowExpense.ownerOID ||
      (this.props.owner || {}).userOID ||
      agentOid ||
      user.userOID;
    if (expenseReport) {
      userOID = expenseReport.applicantOID;
    }
    // 差补费用类型金额修改配置：默认是1001
    // 1001:差补费用类型金额不可编辑, 1002:差补费用类型金额不可改大 , 1003:差补费用类型金额正常修改
    let subsidyAmountEditConfig =
      invoiceUserFp["allowance.amount.modify"] || 1001;
    let isAmountDisabled =
      expenseReport &&
      expenseReport.formCode &&
      !["MCD1001", "MCD2001", "MCD3001"].includes(expenseReport.formCode);
    //是否为差补费用类型
    let isSubsidyType = isAmountDisabled
      ? false
      : nowExpense.expenseTypeSubsidyType === 1;
    let thirdEditAmount =
      !this.props.readOnly &&
      expenseType.readonly &&
      expenseType.isAmountEditable;
    let thirdEditField = !this.props.readOnly && expenseType.readonly;
    let amount =
      this.state.didiArr.length > 1 && this.state.didiArr[0].total
      ? Number(this.state.didiArr[0].total)
      : readOnly && !thirdEditAmount && !auditAmountEditing
        ? nowExpense.amount
          : Number(getFieldValue("amount"));
    let actualCurrencyRate =
      (readOnly && !auditAmountEditing
        ? nowExpense.actualCurrencyRate
        : getFieldValue("actualCurrencyRate")) || 0;
    let isBaseCurrency =
      baseCurrency.currencyCode && nowCurrency.currencyCode
        ? baseCurrency.currencyCode === nowCurrency.currencyCode
        : true;
    let showRateDescription =
      !isNaN(amount) && (amount > 0 || amount > 0) && !isBaseCurrency;
    let rateDescription = `${messages("my-account.key115" /*企业汇率*/)}：`;
    let rateDeviation = 0;
    if (showRateDescription) {
      rateDeviation = (
        (Math.abs(actualCurrencyRate - nowCurrency.rate) / nowCurrency.rate) *
        100
      ).toFixed(1);
      rateDescription += Number(nowCurrency.rate || 0).toFixed(2);
      rateDescription += actualCurrencyRate > nowCurrency.rate ? " + " : " - ";
      rateDescription +=
        rateDeviation +
        `%，${messages("common.base.currency.amount") /*本位币金额*/}：`;
      rateDescription += currencyPrecisionCal(
        baseCurrency.currencyCode,
        actualCurrencyRate * amount
      );
    }
    let pasteInvoiceNeeded = expenseType.pasteInvoiceNeeded;
    let thirdWithReceipt = nowExpense.withReceipt;
    let hasInvoiceInstead =
      !profile["invoice.instead.disabled"] &&
      (readOnly ? thirdWithReceipt : pasteInvoiceNeeded);
    let invoiceInsteadText = profile["invoice.instead.comments"]
      ? messages("my-account.key104" /*是否备注*/)
      : messages("my-account.key105" /*是否替票*/);
    let invoiceInsteadReasonText = profile["invoice.instead.comments"]
      ? messages("my-account.key106" /*备注理由*/)
      : messages("my-account.key107" /*替票理由*/);
    let invoiceInstead =
      hasInvoiceInstead &&
      (readOnly && this.props.readOnly
        ? nowExpense.invoiceInstead
        : getFieldValue("invoiceInstead"));
    let hasExpenseApportion = expenseType.id && expenseReport && !isNaN(amount);
    const apportionEnable = readOnly
      ? nowExpense.apportionUsed
      : expenseType.erApportionEnabled;
    let hasEditedAmount =
      nowExpense.amount !== nowExpense.originalAmount ||
      (nowExpense.actualCurrencyRate &&
        nowExpense.actualCurrencyRate !==
          nowExpense.originalActualCurrencyRate);
    let mileageAllowanceExpenseDTO = nowExpense.mileageAllowanceExpenseDTO;
    //第三方费用滴滴不可编辑发票,但是他的withReceipt是true
    let isDiDi = expenseType.messageKey === "expense.type.didi";
    const isMile = expenseType.messageKey === "private.car.for.public";
    let thirdEditInvoice =
      !this.props.readOnly &&
      expenseType.readonly &&
      !isDiDi &&
      thirdWithReceipt &&
      (!isMile || (isMile && lovEditable));
    let currencyCodeDisabled =
      isSubsidyType ||
      isMile ||
      (expenseReport &&
        expenseReport.currencyCode !== this.props.company.baseCurrency) ||
      (expenseReport &&
        expenseReport.currencyCode === this.props.company.baseCurrency &&
        this.checkFunctionProfiles("web.invoice.keep.consistent.with.expense", [
          true,
        ]));
    let invoiceSettingArea = (
      <div>
        {hasInvoiceInstead && (
          <FormItem {...formItemLayout} label={invoiceInsteadText}>
            {nowExpense.invoiceInstead
              ? messages("common.yes")
              : messages("common.no")}
          </FormItem>
        )}

        {invoiceInstead && (
          <FormItem {...formItemLayout} label={invoiceInsteadReasonText}>
            {nowExpense.invoiceInsteadReason}
          </FormItem>
        )}

        {thirdWithReceipt &&
          !invoiceUserFp["account.book.VAT.special.invoice.disabled"] && (
            <FormItem
              {...formItemLayout}
              label={messages("my-account.key1" /*录入发票*/)}
              required={expenseType.invoiceRequired}
            >
              {expenseType.multipleInvoiceSupported ||
              receiptList.length < 1 ? (
                <div className="add-invoice-container">
                  {!readOnly || this.getAuditOperateAuth() ? (
                    this.renderButtonAddInvoice(receiptList, showOCRFlag)
                  ) : (
                    <div>
                      {messages(
                        receiptList.length < 1 ? "common.no" : "common.yes"
                      )}
                    </div>
                  )}
                </div>
              ) : (
                <div>{messages("common.yes")}</div>
              )}
            </FormItem>
          )}
      </div>
    );
    let originNonVat =
      nowExpense.originalApprovedNonVat !== null
        ? this.filterMoney(
            nowExpense.originalApprovedNonVat,
            invoiceCurrencyCodePrecision
          )
        : this.filterMoney(
            nowExpense.originalAmount,
            invoiceCurrencyCodePrecision
          );
    let originVat = nowExpense.originalApprovedVat
      ? this.filterMoney(
          nowExpense.originalApprovedVat,
          queryCurrencyPrecision(invoiceCurrencyCodePrecision)
        )
      : currencyPrecisionCal(invoiceCurrencyCodePrecision, 0);
    let invoiceSiteIndex = 0;
    let lastInvoiceIndex, nextInvoiceIndex;
    let ifAssignmentCurrentInvoice = false;
    //获取上一条，下一条费用位置。
    showExpenseReportInvoices &&
      showExpenseReportInvoices.map((item, index) => {
        if (item.invoiceOID === nowExpense.invoiceOID) {
          invoiceSiteIndex = index;
          ifAssignmentCurrentInvoice = true;
        } else {
          if (!ifAssignmentCurrentInvoice) {
            lastInvoiceIndex = index;
          }
          if (ifAssignmentCurrentInvoice && index - 1 === invoiceSiteIndex) {
            nextInvoiceIndex = index;
          }
        }
      });
    //获取发票发生日期
    let receiptDate = undefined;
    // console.log('receiptList', receiptList)
    receiptList.map((receiptItem) => {
      if (
        receiptItem.billingTime &&
        (!receiptDate || receiptItem.billingTime < receiptDate)
      ) {
        receiptDate = receiptItem.billingTime;
      }
    });
    let checkedNum = 0;
    let recordOriAmount = 0;
    let oriCurCod = "";
    const businessCardTotalAmount = businessCardConsumptions.reduce(
      (pre, now) => {
        if (!now.relationMap) {
          now.relationMap = {};
        }
        const keys = Object.keys(now.relationMap);
        const recordAmount = keys.reduce((preKeyAmount, key) => {
          let keyAmount = 0;
          if (now.relationMap[key] && now.relationMap[key].length > 0) {
            keyAmount = now.relationMap[key].reduce((total, relation) => {
              if (relation.amount !== 0 && relation.checked) {
                checkedNum++;
                if (!oriCurCod || oriCurCod.length === 0) {
                  oriCurCod = relation.oriCod;
                }
                recordOriAmount = recordOriAmount + relation.oriAmount;
                return relation.amount + total;
              }
              return 0 + total;
            }, 0);
          }
          return preKeyAmount + keyAmount;
        }, 0);
        return pre + recordAmount;
      },
      0
    );
    const isOfficialCard =
      expenseReport && expenseReport.isOfficialCard
        ? expenseReport.isOfficialCard
        : undefined;
    let thirdUser = undefined;
    if (expenseReport && expenseReport.formCode === "BX006") {
      expenseReport.custFormValues.map((item) => {
        if (item.fieldName === "费用确认人") {
          thirdUser = item.showValue;
        }
      });
    }
    /**
     * 增加是否展示“关联公务卡”按钮的条件(替换之前的只根据props里的businessCardEnabled)
     * 1、该费用已经关联了公务卡
     * 2、费用申请人所在公司和招商银行有关系且有公务卡消费记录
     * 2021-06-04 https://pmo.mcd.com.cn/jira/browse/TES-1963
     * 费用申请人不剩下公务卡消费记录或公司与招行无关时，依旧展示关联公务卡按钮，选择页面显示文本"没有更多数据了"
     */
    let showBusinessCardBtn = true;
    let officeCardShowTrue = officeCardShow;
    if (type === 1) {
      showBusinessCardBtn = false; // 公务卡生成费用不展示“关联公务卡”按钮
    } else {
      if (isDiDiChange) {
        //滴滴费用不展示 关联公务卡
        showBusinessCardBtn = false;
      } else if (!businessCardEnabledObj.companyEnable) {
        showBusinessCardBtn = true; // 公司与招行无关的员工新建费用页面依旧展示关联公务卡
      } else {
        if (businessCardEnabledObj.remainData) {
          showBusinessCardBtn = true; // 如果费用申请人有剩余的公务卡消费数据，则展示关联公务卡
        } else {
          if (checkedNum > 0) {
            officeCardShowTrue = true;
            showBusinessCardBtn = true; // 当费用申请人不剩下公务卡消费记录但是这个费用有关联公务卡消费记录时展示关联公务卡
          } else {
            showBusinessCardBtn = true; // 当费用申请人不剩下公务卡消费记录且这个费用没有关联公务卡消费记录时依旧展示关联公务卡
          }
        }
      }
    }
    let didiCardArr= [];
    const initFlag =  this.state.didiArr.length !== 0;
    didiCardArr = initFlag ?  this.state.didiArr : (this.props.params.didiExpenseInfo || []);//不为新建费用时
    // console.log("this.props.type === 2 || this.props.officialCard || (isMile && !lovEditable")
    // console.log("this.props.type", this.props.type)
    // console.log("this.props.officialCard", this.props.officialCard)
    // console.log("isMile && !lovEditable", isMile && !lovEditable)
    // console.log("officeCardShowTrue", officeCardShowTrue);
    // console.log("isAmountDisabled", isAmountDisabled);
    // console.log(this.props, '555555555555555');
    // console.log(this.props.params.didiExpenseInfo, '444444444444');
    console.log(amount, 'amount11');
    console.log(this.props.params.didiExpenseInfo,'this.props.params.didiExpenseInfo');

    let departureTime = '';
    didiCardArr && didiCardArr.map(i=>{
      if (departureTime == '') {
        departureTime = i.departureTime
      } else if(moment(departureTime).diff(moment(i.departureTime),'days') > 0) {
        departureTime = i.departureTime
      }
    })

    window.didiCardArr = didiCardArr
    window.moment = moment
    window.departureTime = departureTime

    


    return expenseLoading ? (
      <Spin />
    ) : (
      <DivExpense show={showExpenseDom}>
        <div className={`expense-container page-${nowPage}`}>
          <Row gutter={30} className="expense-container-row">
            <Col className="expense-type" span={12}>
              <div className="expense-type-box" style={{height:'90%'}}>
                {this.renderExpenseSourceArea()}
              </div>
            </Col>
            <Col span={12} className="expense-form">
              <div
                className="expense-form-box"
                style={{ position: "relative" }}
                  ref="expenseFormBox"
              >
                {nowExpense &&
                  nowExpense.invoiceLabels &&
                  nowExpense.invoiceLabels.length > 0 && (
                    <div className="tip-wrap">
                      {nowExpense.invoiceLabels
                        .filter((item) => item.level !== "INFO")
                        .map((item) => (
                          <Alert
                            message={this.showMessage(item)}
                            key={item.name}
                            type={item.level === "ERROR" ? "error" : "info"}
                            showIcon
                          />
                        ))}
                      {nowExpense.invoiceLabels.filter(
                        (item) => item.level === "INFO"
                      ).length > 0 && (
                        <Alert
                          message={nowExpense.invoiceLabels
                            .filter((item) => item.level === "INFO")
                            .map((item) => item.name)
                            .join("/")}
                          type="info"
                          showIcon
                        />
                      )}
                    </div>
                  )}
                {type === 2 &&
                this.props.didiOrderKeys &&
                this.props.didiOrderKeys.length > 0 ? (
                  <div className={"didiNoInvoice"}>
                    <Icon
                      style={{
                        color: "#AABBD2",
                        fontSize: "14px",
                        marginRight: "8px",
                      }}
                      type="info-circle"
                    />
                    无票
                  </div>
                ) : null}
                  <Form onSubmit={this.handleSave}>
                  <If
                    value={
                      !window.ISIE9 &&
                      nowExpense.expenseTypeSubsidyType === 1 &&
                      subsidyData.length > 0
                    }
                  >
                    <div style={{ height: 31 }}>
                      <a
                        onClick={this.goBottom}
                        style={{ position: "absolute", right: 20 }}
                      >
                        {messages("my-account.key118" /*补贴明细*/)}{" "}
                        <Icon type="arrow-down" />
                      </a>
                    </div>
                  </If>
                  <Spin spinning={loading}>
                    {/* 卡片显示录入发票信息 */}
                    {receiptList && receiptList.length > 0 && (
                      <Invoice
                        invoiceList={receiptList}
                        disabledEdit={
                          readOnly && //费用只读
                          !thirdEditInvoice && //不是第三方可编辑发票
                          !this.getAuditOperateAuth() //财务不可编辑费用
                        }
                        createType={this.getAuditOperateAuth() ? 2 : 1} //创建类型：1.用户操作类型2.财务操作类型
                        isPreViewCallBack={
                          audit || view || pay || auditCapability || approve
                        }
                        handlePreViewCallBack={(file) =>
                          this.handlePreviewFile(file)
                        }
                        handleDelete={(invoice, index) =>
                          this.handleDeleteReceipt(invoice, index)
                        }
                        handleEdit={(invoice, index) =>
                          this.receiptOperateSceneInit(3, invoice, index)
                        }
                      />
                    )}
                    <div className="expense-type-container">
                    {/* {businessCardConsumptions.length > 0 && (
                        <BusinessCard
                          readOnly={this.props.readOnly}
                          cardList={businessCardConsumptions}
                          invoiceOID={nowExpense.invoiceOID}
                          businessCardType={businessCardType}
                          currencyPrecision={invoiceCurrencyCodePrecision}
                          handleDeleteCard={this.handleDeleteCard}
                        />
                      )} */}
                      <If value={expenseType.promptEnabled && promptThan300}>
                        <FormItem {...formItemLayout} label=" " colon={false}>
                          <a onClick={this.handleShowFormDesc}>
                            <Icon type="info-circle" />{" "}
                            {expenseType.promptTitle}
                          </a>
                        </FormItem>
                        </If>
                        <DiDiCard
                          readOnly={this.props.readOnly}
                          cardList={this.state.didiArr}
                          invoiceOID={nowExpense.invoiceOID}
                          businessCardType={businessCardType}
                          currencyPrecision={invoiceCurrencyCodePrecision}
                          handleDeleteCard={this.handleDeleteCards}
                        />
                      {readOnly ? (
                        <div className="expense-read-only">
                           {businessCardConsumptions.length > 0 && (
                        <BusinessCard
                          readOnly={this.props.readOnly}
                          cardList={businessCardConsumptions}
                          invoiceOID={nowExpense.invoiceOID}
                          businessCardType={businessCardType}
                          currencyPrecision={invoiceCurrencyCodePrecision}
                          handleDeleteCard={this.handleDeleteCard}
                        />
                      )}
                          <FormItem
                            {...formItemLayout}
                            label={
                              <img
                                className="expense-type-img"
                                src={expenseType.iconURL}
                                onError={(e) =>
                                  (e.target.src = defaultExpenseTypeIcon)
                                }
                              />
                            }
                            colon={false}
                            className="expense-read-only-base"
                          >
                            <div className="expense-type-name">
                              {expenseType.name}
                            </div>
                            <div className="expense-type-amount">
                              {thirdEditField
                                ? getFieldDecorator("createdDate", {
                                    initialValue: moment(
                                      nowExpense.createdDate
                                    ),
                                    rules: [
                                      {
                                        required: true,
                                        message: messages(
                                          "common.please.select"
                                        ),
                                      },
                                    ],
                                  })(
                                    <DatePicker
                                      format={
                                        expenseType.timeSupported
                                          ? "YYYY-MM-DD HH:mm"
                                          : "YYYY-MM-DD"
                                      }
                                      showTime={!!expenseType.timeSupported}
                                      allowClear={false}
                                      getCalendarContainer={
                                        this.getPopupContainer
                                      }
                                      width={"100%"}
                                    />
                                  )
                                : new Date(nowExpense.createdDate).format(
                                    expenseType.timeSupported
                                      ? "yyyy-MM-dd hh:mm"
                                      : "yyyy-MM-dd"
                                  )}
                              <br />
                              <b>
                                {thirdEditAmount
                                  ? getFieldDecorator("invoiceCurrencyCode", {
                                      rules: [
                                        {
                                          required: true,
                                          message: messages(
                                            "common.please.select"
                                          ),
                                        },
                                      ],
                                      initialValue:
                                        nowExpense.invoiceCurrencyCode,
                                    })(
                                      <Select
                                        dropdownMatchSelectWidth={false}
                                        style={{ width: "50%" }}
                                        getPopupContainer={
                                          this.getPopupContainer
                                        }
                                        onChange={this.handleChangeCurrency}
                                        disabled={isMile}
                                        placeholder={
                                          messages(
                                            "common.please.select"
                                          ) /* 请选择 */
                                        }
                                      >
                                        {currencyList.map((item) => {
                                          return (
                                            <Option key={item.currency}>
                                              {item.currency}
                                              {this.props.language.code ===
                                              "zh_cn"
                                                ? ` ${item.currencyName}`
                                                : ""}
                                            </Option>
                                          );
                                        })}
                                      </Select>
                                    )
                                  : nowExpense.invoiceCurrencyCode}
                                &nbsp;&nbsp;
                                {auditAmountEditing ||
                                thirdEditAmount ||
                                this.props.type === 2
                                  ? getFieldDecorator("amount", {
                                      initialValue: nowExpense.amount,
                                      rules: [
                                        {
                                          required: true,
                                          message: messages(
                                            "common.please.enter"
                                          ),
                                        },
                                        {
                                          async validator(
                                            rule,
                                            value,
                                            callback
                                          ) {
                                            if (getAuditOperateAuth()) {
                                              if (
                                                value >
                                                nowExpense.originalAmount
                                              ) {
                                                throw new Error(
                                                  "核定金额不能大于原金额"
                                                );
                                              }
                                            }
                                          },
                                        },
                                      ],
                                    })(
                                      <InputNumber
                                        precision={invoiceCurrencyCodePrecision}
                                        step={
                                          invoiceCurrencyCodePrecision
                                            ? 1 /
                                              Math.pow(
                                                10,
                                                invoiceCurrencyCodePrecision
                                              )
                                            : 1
                                        }
                                        min={-1000000000}
                                        max={1000000000}
                                        style={{ width: "40%", marginTop: 6 }}
                                        onChange={this.handleToTalMoneyChange}
                                      />
                                    )
                                  : this.filterMoney(
                                      nowExpense.amount,
                                      invoiceCurrencyCodePrecision
                                    )}
                              </b>
                              {!auditAmountEditing &&
                                this.getAuditOperateAuth() &&
                                this.props.expenseReport.formCode !== "BX002" &&
                                this.props.expenseReport.formCode !==
                                  "BX004" && (
                                  <a
                                    className="audit-edit-link"
                                    onClick={this.handleEditAuditAmount}
                                  >
                                    {messages("my-account.key130" /*核定金额*/)}
                                  </a>
                                )}
                            </div>
                            {showRateDescription &&
                              !isBaseCurrency &&
                              !auditAmountEditing && (
                                <div className="expense-rate-description">
                                  {messages("my-account.key131" /*实际汇率*/)}：
                                  {actualCurrencyRate.toFixed(2)} <br />
                                  {rateDescription}
                                </div>
                              )}
                            {auditAmountEditing && isNonVat && (
                              <div>
                                <Row style={{ marginTop: "10px" }}>
                                  <span style={{ float: "left" }}>
                                    {messages("my-account.key132" /*原币金额*/)}
                                    ：
                                  </span>
                                  <Col span={10} style={{ marginLeft: "10px" }}>
                                    {getFieldDecorator(
                                      "originalApprovedNonVat"
                                    )(
                                      <InputNumber
                                        style={{ width: "100%" }}
                                        precision={invoiceCurrencyCodePrecision}
                                        step={
                                          invoiceCurrencyCodePrecision
                                            ? 1 /
                                              Math.pow(
                                                10,
                                                invoiceCurrencyCodePrecision
                                              )
                                            : 1
                                        }
                                        onBlur={this.weatherChange}
                                        onFocus={this.blurSetValue}
                                        onChange={
                                          this.changeOriginalApprovedNonVat
                                        }
                                      />
                                    )}
                                  </Col>
                                </Row>
                                <Row style={{ marginTop: "10px" }}>
                                  <span style={{ float: "left" }}>
                                    {messages("my-account.key133" /*原币税额*/)}
                                    ：
                                  </span>
                                  <Col span={10} style={{ marginLeft: "10px" }}>
                                    {getFieldDecorator("originalApprovedVat")(
                                      <InputNumber
                                        style={{ width: "100%" }}
                                        precision={invoiceCurrencyCodePrecision}
                                        step={
                                          invoiceCurrencyCodePrecision
                                            ? 1 /
                                              Math.pow(
                                                10,
                                                invoiceCurrencyCodePrecision
                                              )
                                            : 1
                                        }
                                        disabled={true}
                                      />
                                    )}
                                  </Col>
                                </Row>
                              </div>
                            )}

                            {auditAmountEditing && !isBaseCurrency && (
                              <Row style={{ marginTop: "10px" }}>
                                <span style={{ float: "left" }}>
                                  {messages("common.currency.rate")}:
                                </span>
                                <Col span={10} style={{ marginLeft: "10px" }}>
                                  {getFieldDecorator("actualCurrencyRate", {
                                    rules: [
                                      {
                                        required: true,
                                        message: messages(
                                          "common.please.enter"
                                        ),
                                      },
                                    ],
                                  })(
                                    <InputNumber
                                      step={0.01}
                                      precision={2}
                                      style={{ width: "100%" }}
                                      disabled={!prohibitExchangeRateTol}
                                      min={0}
                                    />
                                  )}
                                </Col>
                                <div>
                                  <br />
                                  <Alert
                                    message={rateDescription}
                                    type={
                                      rateDeviation > prohibitExchangeRateTol
                                        ? "error"
                                        : rateDeviation > warnExchangeRateTol
                                        ? "warning"
                                        : "info"
                                    }
                                    showIcon
                                    className="rate-description"
                                  />
                                </div>
                              </Row>
                            )}
                            {(hasEditedAmount || auditAmountEditing) && (
                              <Tag>
                                {messages("my-account.key134" /*原金额*/)}：
                                {this.filterMoney(
                                  nowExpense.originalAmount,
                                  invoiceCurrencyCodePrecision
                                )}
                                &nbsp;&nbsp;
                                {showRateDescription &&
                                  !isBaseCurrency &&
                                  `${messages(
                                    "my-account.key135" /*原汇率*/
                                  )}：${nowExpense.originalActualCurrencyRate}`}
                              </Tag>
                            )}
                            {/*fix bug 24556 32886 原币金额和税额是费用所在报销单提交后显示的，编辑状态下不显示*/}
                            <If
                              value={
                                expenseReport && expenseReport.status !== 1001
                              }
                            >
                              <Tag>
                                {messages("my-account.key132" /*原币金额*/)}：
                                {originNonVat} &nbsp;&nbsp;
                                {messages("my-account.key133" /*原币税额*/)}：
                                {originVat}
                              </Tag>
                            </If>
                            {auditAmountEditing && (
                              <div>
                                <Button
                                  type="primary"
                                  style={{ marginRight: 8 }}
                                  onClick={this.handleSaveAuditAmount}
                                  disabled={
                                    rateDeviation > prohibitExchangeRateTol
                                  }
                                  loading={savingAuditAmount}
                                >
                                  {messages("common.save")}
                                </Button>
                                <Button
                                  onClick={() =>
                                    this.setState({ auditAmountEditing: false })
                                  }
                                >
                                  {messages("common.cancel")}
                                </Button>
                              </div>
                            )}
                          </FormItem>
                          {this.getAuditOperateAuth() && (
                            <FormItem
                              {...formItemLayout}
                              label={messages("my-account.key244") /*能否抵扣*/}
                            >
                              <Switch
                                checked={nowExpense.vatInvoice}
                                size="small"
                                loading={loadingCheck}
                                onClick={(check) =>
                                  this.handleCheckVatInvoice(check)
                                }
                              />
                            </FormItem>
                          )}
                          <FormItem
                            {...formItemLayout}
                            label={messages("my-account.key171") /*费用归属人*/}
                          >
                            {this.props.agentName ||
                            (this.props.expenseReport || {}).formCode ===
                              "BX006"
                              ? (this.props.expenseReport || {}).carPerson
                                  .approvalName
                              : (this.props.expenseReport || {})
                                  .applicantName ||
                                (nowExpense.owner &&
                                  nowExpense.owner.fullName) ||
                                this.props.user.fullName}
                          </FormItem>
                          {/* 里程补贴显示*/}
                          {isMile &&
                            unitPriceMode &&
                            !nowExpense.mileageAllowanceExpenseDTO &&
                            this.renderMileageForm()}
                          {/*需求 4036*/}
                          <If value={expenseType.valid}>
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.number") /*数量*/}
                            >
                              {nowExpense.number}
                            </FormItem>
                            <FormItem
                              {...formItemLayout}
                              label={`${messages("common.price")}/${
                                unitInfo[expenseType.unit] || ""
                              }`}
                            >
                              {nowExpense.unitPrice &&
                                Number(nowExpense.unitPrice).toFixed(
                                  queryCurrencyPrecision(
                                    invoiceCurrencyCodePrecision
                                  )
                                )}
                            </FormItem>
                          </If>
                          {thirdEditInvoice
                            ? this.renderInvoiceEditingArea()
                            : isDiDi || (isMile && !lovEditable)
                            ? null
                            : invoiceSettingArea}
                          {[
                            "MCD1018",
                            "MCD1024",
                            "MCD1214",
                            "MCD1221",
                            "MCD1229",
                            "MCD1053",
                          ].includes(expenseType.code) && (
                            <TravelShare
                              amount={amount}
                              currencyCode={nowCurrency.currencyCode}
                              currencyList={currencyList}
                              userName={
                                (this.props.expenseReport || {})
                                  .applicantName ||
                                (nowExpense.owner &&
                                  nowExpense.owner.fullName) ||
                                this.props.agentName ||
                                this.props.user.fullName
                              }
                              userOID={userOID}
                              onChange={this.changeShareData}
                              nowExpense={nowExpense}
                              feeAcknowledgers={this.state.feeAcknowledgers}
                              onChangeSwitch={this.changeSwitch}
                              readOnly={readOnly && !thirdEditField}
                            />
                          )}
                          {!this.props.readOnly &&
                            showBusinessCardBtn &&
                            (type === 3
                              ? (isOfficialCard && isOfficialCard !== "0") ||
                                isOfficialCard === 1
                              : true) && (
                              <FormItem
                                {...formItemLayout}
                                label={
                                  type === 2
                                    ? "消费账单"
                                    : messages(
                                        "mcd.myAccount.publicServiceCardBankBill.linkOfficialCard"
                                      ) /* 关联公务卡 */
                                }
                              >
                                <div
                                  style={{
                                    color: "#77A9F9",
                                    cursor: "pointer",
                                  }}
                                  onClick={() =>
                                    this.setState({
                                      nowPage: "card",
                                      typeSource: "businessCard",
                                      fromExpense: true,
                                      isBusinessCardMore: false,
                                    })
                                  }
                                >
                                  <Icon type="plus" />
                                  关联公务卡消费记录
                                  <div
                                    style={{
                                      color: "#4E5B71",
                                      fontSize: "12px",
                                      height: "12px",
                                      lineHeight: "12px",
                                    }}
                                  >
                                    (已选中&nbsp;
                                    <span style={{ fontWeight: "bold" }}>
                                      {checkedNum}
                                    </span>
                                    &nbsp; 笔消费记录，合计&nbsp;
                                    <span style={{ fontWeight: "bold" }}>
                                      {oriCurCod}&nbsp;
                                      {this.addCommas(recordOriAmount)}
                                    </span>
                                    <span>/</span>
                                    <span style={{ fontWeight: "bold" }}>
                                      {nowCurrency.currency}&nbsp;
                                      {this.addCommas(businessCardTotalAmount)}
                                    </span>
                                    )
                                  </div>
                                </div>
                              </FormItem>
                            )}
                          {(nowExpense.data || []).map((field) => {
                            let formItemVisible = true;
                            if (field.messageKey === "company.payment.type") {
                              //fix bug 28777
                              nowExpense.data.map((fieldItem) => {
                                if (fieldItem.fieldType === "COMPANY_PAID") {
                                  formItemVisible = fieldItem.value === "1002";
                                }
                              });
                            }
                            if (field.messageKey === "associate.application") {
                              const value = this.state.showAssociateApplication;
                              if (typeof value === "boolean") {
                                formItemVisible = value;
                              }
                            }
                            return (
                              formItemVisible &&
                              field.showOnList &&
                              (!unitPriceMode ||
                                (!nowExpense.mileageAllowanceExpenseDTO &&
                                  unitPriceMode &&
                                  !~mileageMessageKey.indexOf(
                                    field.messageKey
                                  ))) &&
                              ((field.name == "参与人清单" ||
                                field.name == "接收人清单") &&
                              !this.state.isShowPlayerList ? (
                                ""
                              ) : (
                                <FormItem
                                  {...formItemLayout}
                                  label={field.name}
                                  key={`${field.fieldOID}`}
                                >
                                  {thirdEditField && field.editable
                                    ? getFieldDecorator(`${field.fieldOID}`, {
                                        rules: [
                                          {
                                            required: [
                                              "associate.application",
                                              "public.assembly",
                                            ].includes(field.messageKey)
                                              ? field.isHidden
                                                ? field.isSwitchOn
                                                  ? field.name ===
                                                      "接收人情况是否与申请单不同" ||
                                                    field.name ===
                                                      "参与人情况是否与申请单不同"
                                                    ? false
                                                    : field.required
                                                  : false
                                                : field.required
                                              : field.required,
                                            message:
                                              field.name ===
                                              "未通过TMC购买国内机票申请"
                                                ? "请关联未通过TMC购买国内机票申请"
                                                : messages(
                                                    "common.name.is.required",
                                                    { name: field.name }
                                                  ),
                                          },
                                          ...this.getFieldRules(
                                            field,
                                            nowExpense.data
                                          ),
                                        ],
                                        valuePropName: ~[
                                          "COMPANY_PAID",
                                          "BOOLEAN",
                                        ].indexOf(field.fieldType)
                                          ? "checked"
                                          : "value",
                                        initialValue: this.getFieldDefaultValue(
                                          field.fieldType,
                                          field.value,
                                          field.showValue,
                                          field
                                        ),
                                      })(this.switchField(field, isSubsidyType))
                                    : expenseService.getFieldName(
                                        field,
                                        isWithTime,
                                        this.getAuditOperateAuth(
                                          !!profile["finance.audit.edit.enable"]
                                        ),
                                        expenseReport,
                                        nowExpense,
                                        this.skipApplication,
                                        this.changeFieldValue,
                                        isSubsidyType,
                                        this.state.expenseTypeCache || {
                                          fields: [],
                                        }
                                      )}
                                </FormItem>
                              ))
                            );
                          })}
                          {hasExpenseApportion &&
                            isWorthAmount &&
                            nowCurrency.currencyCode && (
                              <ExpenseApportion
                                value={expenseApportion}
                                amount={amount}
                                taxRate={taxRate}
                                apportionEnable={apportionEnable}
                                currencyCode={nowCurrency.currencyCode}
                                actualApportionAmount={actualApportionAmount}
                                readOnly={readOnly && !thirdEditField}
                                expenseReportOID={
                                  expenseReport.expenseReportOID
                                }
                                formOID={expenseReport.formOID}
                                invoiceOID={nowExpense.invoiceOID}
                                expenseTypeId={expenseType.id}
                                ownerOID={userOID}
                                costCenterItemsApportion={
                                  costCenterItemsApportion
                                }
                                expenseReport={expenseReport}
                                receiptList={receiptList || []}
                                onChange={this.handleChangeExpenseApportion}
                                jobInfo={jobInfo}
                                expenseTypeCode={expenseType.code}
                                costAttribute={expenseType.costAttribute}
                                expenseTypeOid={expenseType.expenseTypeOID}
                                createdDate={nowExpense.createdDate}
                                nowDate={this.state.nowDate}
                                modeType={
                                  this.props.nowExpense && !this.props.isCopy
                                }
                                expenseTypeName={expenseType.name}
                              />
                              )}
                          {expenseType.code === "MCD1027" ||
                          expenseType.code === "MCD1410" ? (
                            <FormItem
                              {...formItemLayout}
                              label="私车公用使用费用报告"
                            >
                              {/*<a href="https://tes-static-1256351955.cos.ap-shanghai.myqcloud.com/208e5756-cb85-444c-b6ef-02624fea15c6/other/a4626b3e-be39-4c15-8599-7d1d876826a0-%E9%99%84%E4%BB%B6H2-%E7%A7%81%E8%BD%A6%E5%85%AC%E5%8A%A1%E4%BD%BF%E7%94%A8%E8%B4%B9%E7%94%A8%E6%8A%A5%E5%91%8A.xlsx" download="私车公用使用费用报告">私车公用使用费用报告</a>*/}
                              <a
                                href="https://tes-static-1256351955.cos.ap-shanghai.myqcloud.com/208e5756-cb85-444c-b6ef-02624fea15c6/other/c14a97fa-7cc4-406a-952a-7d5c810b1c23-%E9%99%84%E4%BB%B6H1-%E7%A7%81%E8%BD%A6%E5%85%AC%E5%8A%A1%E4%BD%BF%E7%94%A8%E8%B4%B9%E7%94%A8%E6%8A%A5%E5%91%8A.xlsx"
                                download="私车公用使用费用报告"
                              >
                                私车公用使用费用报告
                              </a>
                            </FormItem>
                          ) : (
                            ""
                          )}
                          {audit ||
                          view ||
                          pay ||
                          auditCapability ||
                          approve ? (
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.attachments") /*附件*/}
                              style={{ marginBottom: 12 }}
                              required={this.isRequiredFile()}
                            >
                              <Condition>
                                <If value={window.ISIE9}>
                                  <IeFileUpload
                                    defaultFileList={attachments}
                                    data={{
                                      attachmentType: "INVOICE_IMAGES",
                                      invoiceOid: nowExpense.invoiceOID,
                                    }}
                                    attachmentType="INVOICE_IMAGES"
                                    fileSize={10}
                                    showMaxNum
                                    disabled={
                                      !(
                                        (audit && isWaitForAudit) ||
                                        auditCapability
                                      )
                                    }
                                    uploadUrl={`${config.baseUrl}/api/finance/upload/attachment`}
                                    token={this.props.authToken.access_token}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    handleDelete={this.deleteAttachment}
                                    onChange={this.uploadSuccess}
                                  />
                                </If>
                                <Else>
                                  <FileUpload
                                    defaultFileList={attachments}
                                    data={{
                                      attachmentType: "INVOICE_IMAGES",
                                      invoiceOid: nowExpense.invoiceOID,
                                    }}
                                    attachmentType="INVOICE_IMAGES"
                                    onChange={this.uploadSuccess}
                                    fileSize={10}
                                    isPreViewCallBack
                                    handlePreViewCallBack={(file) =>
                                      this.handlePreviewFile(file)
                                    }
                                    isShowDefault
                                    showMaxNum
                                    handleDelete={this.deleteAttachment}
                                    disabled={
                                      !(
                                        (audit && isWaitForAudit) ||
                                        auditCapability
                                      )
                                    }
                                    uploadUrl={`${config.baseUrl}/api/finance/upload/attachment`}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                  />
                                </Else>
                              </Condition>
                            </FormItem>
                          ) : thirdEditField ? (
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.attachments") /*附件*/}
                              help={
                                messages("common.max.upload.attachment", {
                                  max: 9,
                                }) /*最多上传9张图片*/
                              }
                              style={{ marginBottom: 12 }}
                              required={this.isRequiredFile()}
                            >
                              <Condition>
                                <If value={window.ISIE9}>
                                  <IeFileUpload
                                    defaultFileList={attachments}
                                    attachmentType="INVOICE_IMAGES"
                                    token={this.props.authToken.access_token}
                                    isShowDefault
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    onChange={this.uploadSuccess}
                                  />
                                </If>
                                <Else>
                                  <FileUpload
                                    defaultFileList={attachments}
                                    attachmentType="INVOICE_IMAGES"
                                    onChange={this.uploadSuccess}
                                    isShowDefault
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                  />
                                </Else>
                              </Condition>
                            </FormItem>
                          ) : (
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.attachments") /*附件*/}
                            >
                              {attachments && attachments.length > 0 ? (
                                <FileUpload
                                  defaultFileList={attachments}
                                  attachmentType="INVOICE_IMAGES"
                                  isShowDefault
                                  disabled
                                />
                              ) : (
                                "-"
                              )}
                            </FormItem>
                          )}
                          {/* 3、账本：如关联公务卡，无需必填，费用保存时校验，强管控 */}
                          {/* 配置了类型并且没关联公务卡 才展示 */}
                          {!notShowFileList.includes(expenseType.code) && businessCardConsumptions.length === 0 && type !== 1 &&  (
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.attachments.electronic.payment") /*电子支付凭证*/}
                              style={{ marginBottom: 12 }}
                              required={this.isRequiredNewFile(expenseType)}

                            >
                              <Condition>
                                <If value={window.ISIE9}>
                                  <IeFileUpload
                                    multiple
                                    defaultFileList={electronicAttachments}
                                    attachmentType="INVOICE_IMAGES"
                                    fileSize={10}
                                    maxNum={99}
                                    showMaxNum
                                    isShowDefault
                                    token={this.props.authToken.access_token}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    disabled
                                  />
                                </If>
                                <Else>
                                  <FileUpload
                                    multiple
                                    defaultFileList={electronicAttachments}
                                    attachmentType="INVOICE_IMAGES"
                                    isShowDefault
                                    maxNum={99}
                                    showMaxNum
                                    fileSize={10}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    disabled
                                  />
                                </Else>
                              </Condition>
                            </FormItem>
                          )}

                          {thirdEditField ? (
                            <FormItem
                              {...formItemLayout}
                              label={
                                messages("common.subjectmatter") /*事由说明*/
                              }
                            >
                              {getFieldDecorator("comment", {
                                initialValue: nowExpense.comment,
                                rules: [
                                  {
                                    required: expenseType.titleRequired,
                                    message: `${messages(
                                      "common.please.enter"
                                    )}`,
                                    whitespace: true,
                                  },
                                ],
                              })(
                                <TextArea
                                  rows={4}
                                  style={{ width: "100%" }}
                                  maxLength="200"
                                  placeholder={
                                    expenseType.titlePlaceholder ||
                                    `${messages(
                                      "common.please.enter"
                                    )}, ${messages(
                                      "common.max.characters.length",
                                      { max: 200 }
                                    )}`
                                  }
                                />
                              )}
                            </FormItem>
                          ) : (
                            <FormItem
                              {...formItemLayout}
                              label={
                                messages("common.subjectmatter") /*事由说明*/
                              }
                            >
                              {nowExpense.comment || "-"}
                            </FormItem>
                          )}
                        </div>
                        ) : (
                            <div>
                              <FormItem>
                        <BusinessCard
                          readOnly={this.props.readOnly}
                          cardList={businessCardConsumptions}
                          invoiceOID={nowExpense.invoiceOID}
                          businessCardType={businessCardType}
                          currencyPrecision={invoiceCurrencyCodePrecision}
                          handleDeleteCard={this.handleDeleteCard}
                        />
                              </FormItem>
                          {/* 费用类型 */}
                          <FormItem
                            {...formItemLayout}
                            label={messages("common.expense.type") /*费用类型*/}
                            required
                          >
                            {expenseType.id ? (
                              <Card
                                className="expense-card"
                                onClick={() =>
                                  !isSubsidyType &&
                                  expenseType.messageKey !==
                                    "private.car.for.public" &&
                                  this.setState({
                                    nowPage: "type",
                                    typeSource: "expenseType",
                                  })
                                }
                              >
                                <img
                                  src={expenseType.iconURL}
                                  onError={(e) =>
                                    (e.target.src = defaultExpenseTypeIcon)
                                  }
                                />
                                <Popover
                                  content={expenseType.name}
                                  overlayStyle={{ maxWidth: 300 }}
                                  placement="bottom"
                                >
                                  <div className="expense-name">
                                    {expenseType.name}
                                  </div>
                                </Popover>
                              </Card>
                            ) : (
                              <Icon
                                type="question-circle"
                                style={{
                                  color: "#BFBFBF",
                                  fontSize: 40,
                                  cursor: "pointer",
                                }}
                                onClick={() => {
                                  this.setState({
                                    nowPage: "type",
                                    typeSource: "expenseType",
                                  });
                                }}
                              />
                            )}
                              </FormItem>

                          {/* 发生日期 */}
                          <FormItem
                            {...formItemLayout}
                            label={
                              expenseType.oisTipsShow
                                ? this.renderTips(
                                    messages("common.happened.date"),
                                    expenseType.ofieldTips
                                  )
                                : messages("common.happened.date") /*发生日期*/
                            }
                            required
                          >
                            {getFieldDecorator("createdDate", {
                              rules: [
                                {
                                  required: true,
                                  message: messages("common.please.select"),
                                },
                              ],
                              initialValue:
                                this.props.type === 2 &&
                                didiCardArr.length> 0
                                  ? didiCardArr[0]
                                    ? departureTime
                                      ? moment(
                                        departureTime
                                        )
                                      : null
                                    : null
                                  : this.props.officialCard
                                  ? earliestDate
                                  : receiptDate && receiptOperateScene === 1
                                  ? moment(new Date(receiptDate * 1000))
                                  : expenseType.occurDateDefaultValue ===
                                    "CURRENT"
                                  ? moment(new Date())
                                  : undefined,
                            })(
                              <DatePicker
                                format={
                                  expenseType.timeSupported
                                    ? "YYYY-MM-DD HH:mm"
                                    : "YYYY-MM-DD"
                                }
                                showTime={!!expenseType.timeSupported}jin
                                disabledDate={this.disabledStartDate}
                                allowClear={false}
                                style={{ width: "100%" }}
                                onChange={this.handleChangeCreatedDate}
                                disabled={
                                  isDiDiChange
                                    ? true
                                    : expenseType.code === "MCD1028"
                                    ? true
                                    : this.props.type === 2 ||
                                      (isMile && !lovEditable)
                                }
                                getCalendarContainer={this.getPopupContainer}
                              />
                            )}
                          </FormItem>
                          <FormItem
                            {...formItemLayout}
                            label={messages("common.amount") /*金额*/}
                            required
                          >
                            <Col span={10}>
                              <FormItem>
                                {getFieldDecorator("invoiceCurrencyCode", {
                                  rules: [
                                    {
                                      required: true,
                                      message: messages("common.please.select"),
                                    },
                                  ],
                                  initialValue:
                                    this.props.type === 2
                                      ? "CNY"
                                      : this.props.officialCard
                                      ? this.props.posCurCod
                                      : this.props.company.baseCurrency,
                                })(
                                  <Select
                                    placeholder={
                                      messages(
                                        "common.please.select"
                                      ) /* 请选择 */
                                    }
                                    dropdownMatchSelectWidth={false}
                                    disabled={
                                      isDiDiChange
                                        ? true
                                        : officeCardShowTrue
                                        ? true
                                        : isAmountDisabled
                                        ? false
                                        : expenseType.code === "MCD1028"
                                        ? true
                                        : this.props.type === 2 ||
                                          this.props.officialCard ||
                                          currencyCodeDisabled ||
                                          expenseType.valid ||
                                          (isMile && !lovEditable)
                                    }
                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) =>
                                      option.props.children
                                        .toString()
                                        .toLowerCase()
                                        .indexOf(input.toLowerCase()) >= 0
                                    }
                                    getPopupContainer={this.getPopupContainer}
                                    onChange={this.handleChangeCurrency}
                                  >
                                    {currencyList.map((item) => (
                                      <Option key={item.currency}>
                                        {item.currency}
                                        {this.props.language.code === "zh_cn"
                                          ? ` ${item.currencyName}`
                                          : ""}
                                      </Option>
                                    ))}
                                  </Select>
                                )}
                              </FormItem>
                            </Col>
                            <Col span={13} offset={1}>
                              <FormItem>
                                {getFieldDecorator("amount", {
                                  initialValue:
                                  this.state.didiArr.length > 1 && this.state.didiArr[0].total
                                  ? this.state.didiArr[0].total
                                  : type === 2 &&
                                    this.props.params.didiExpenseInfo.length > 1
                                  ? this.props.params.selectedTotal
                                   : type === 2 &&
                                    this.props.params.didiExpenseInfo.length === 1
                                      ? didiAmount
                                      : this.props.officialCard
                                      ? this.props.total
                                      : "",
                                  rules: [
                                    {
                                      required: true,
                                      message: messages("common.please.enter"),
                                    },
                                    {
                                      //fix bug 25064 金额有最大值时，不能显示超过最大值的数据
                                      validator: (rule, value, callback) => {
                                        let max =
                                          isSubsidyType &&
                                          subsidyAmountEditConfig === 1002
                                            ? nowExpense.orderAmount
                                            : 1000000000;
                                        if (
                                          value === "-" ||
                                          Math.abs(value) <= max ||
                                          value === undefined
                                        ) {
                                          callback();
                                        } else {
                                          callback(
                                            messages("my-account.key169", {
                                              arg1: messages(
                                                "my-account.key334"
                                              ) /*10亿*/,
                                            }) /*最大值不能超过{arg1}*/
                                          );
                                        }
                                      },
                                    },
                                  ],
                                })(
                                  <InputNumber
                                    formatter={(value) =>
                                      `${value}`.replace(
                                        /\B(?=(\d{3})+(?!\d))/g,
                                        ","
                                      )
                                    }
                                    parser={(value) =>
                                      value.replace(/\$\s?|(,*)/g, "")
                                    }
                                    style={{ width: "100%" }}
                                    min={-1000000000}
                                    precision={invoiceCurrencyCodePrecision}
                                    step={
                                      invoiceCurrencyCodePrecision
                                        ? 1 /
                                          Math.pow(
                                            10,
                                            invoiceCurrencyCodePrecision
                                          )
                                        : 1
                                    }
                                    onChange={(e) => this.handleChangeAmount(e, expenseType.fields)}
                                    placeholder={messages(
                                      "common.please.enter"
                                    )}
                                    disabled={
                                      isDiDiChange
                                        ? true
                                        : expenseType.code === "MCD1028"
                                        ? true
                                        : officeCardShowTrue
                                        ? true
                                        : isAmountDisabled
                                        ? false
                                        : this.props.officialCard ||
                                          (isMile && unitPriceMode) ||
                                          (isMile && !lovEditable) ||
                                          (isSubsidyType &&
                                            subsidyAmountEditConfig === 1001) ||
                                          expenseType.valid
                                    }
                                  />
                                )}
                              </FormItem>
                            </Col>
                          </FormItem>
                          {expenseType.valid && (
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.number") /*数量*/}
                              required
                            >
                              <Col span={10}>
                                <FormItem>
                                  {getFieldDecorator("number", {
                                    initialValue: nowExpense.number,
                                    rules: [
                                      {
                                        required: true,
                                        message: messages(
                                          "common.please.select"
                                        ),
                                      },
                                    ],
                                  })(
                                    <InputNumber
                                      style={{ width: "100%" }}
                                      precision={2}
                                      min={0}
                                      step={1}
                                      onChange={(e) => this.getAmount(e, true)}
                                      placeholder={messages(
                                        "common.please.enter"
                                      )}
                                    />
                                  )}
                                </FormItem>
                              </Col>
                            </FormItem>
                          )}
                          {expenseType.valid && (
                            <FormItem
                              {...formItemLayout}
                              label={`${messages("common.price")}/${
                                unitInfo[expenseType.unit] || ""
                              }`}
                              required
                            >
                              <Col span={10}>
                                <FormItem>
                                  {getFieldDecorator("unitPrice", {
                                    initialValue: nowExpense.unitPrice,
                                    rules: [
                                      {
                                        required: true,
                                        message: messages(
                                          "common.please.select"
                                        ),
                                      },
                                    ],
                                  })(
                                    <InputNumber
                                      style={{ width: "100%" }}
                                      precision={invoiceCurrencyCodePrecision}
                                      step={
                                        invoiceCurrencyCodePrecision
                                          ? 1 /
                                            Math.pow(
                                              10,
                                              invoiceCurrencyCodePrecision
                                            )
                                          : 1
                                      }
                                      min={0}
                                      onChange={(e) => this.getAmount(e)}
                                      placeholder={messages(
                                        "common.please.enter"
                                      )}
                                    />
                                  )}
                                </FormItem>
                              </Col>
                            </FormItem>
                          )}
                          {/* 里程补贴显示*/}
                          {isMile &&
                            unitPriceMode &&
                            !nowExpense.mileageAllowanceExpenseDTO &&
                            this.renderMileageForm()}
                          {/*汇率*/}
                          {!isBaseCurrency && (
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.currency.rate") /*汇率*/}
                            >
                              <Col span={6}>
                                <div>
                                  {getFieldDecorator("actualCurrencyRate", {
                                    rules: [
                                      {
                                        required: true,
                                        message: messages(
                                          "common.please.enter"
                                        ),
                                      },
                                    ],
                                    initialValue: 1,
                                  })(
                                    <InputNumber
                                      step={0.01}
                                      precision={2}
                                      style={{ width: "100%" }}
                                      min={0}
                                      disabled={
                                        !prohibitExchangeRateTol ||
                                        (isMile && !lovEditable) ||
                                        isBaseCurrency ||
                                        this.checkFunctionProfiles(
                                          "web.expense.rate.edit.disabled",
                                          [true, "true"]
                                        )
                                      }
                                    />
                                  )}
                                </div>
                              </Col>
                              {showRateDescription && (
                                <Col span={17} offset={1}>
                                  <Alert
                                    message={rateDescription}
                                    type={
                                      rateDeviation > prohibitExchangeRateTol
                                        ? "error"
                                        : rateDeviation > warnExchangeRateTol
                                        ? "warning"
                                        : "info"
                                    }
                                    showIcon
                                    className="rate-description"
                                  />
                                </Col>
                              )}
                            </FormItem>
                          )}
                          <FormItem
                            {...formItemLayout}
                            label={messages("my-account.key171") /*费用归属人*/}
                            required
                          >
                            <Input
                              style={{ width: "100%" }}
                              value={
                                thirdUser
                                  ? thirdUser
                                  : (this.props.expenseReport || {})
                                      .applicantName ||
                                    (nowExpense.owner &&
                                      nowExpense.owner.fullName) ||
                                    this.props.agentName ||
                                    this.props.user.fullName
                              }
                              disabled
                            />
                          </FormItem>

                          {/* 费用编辑按钮 */}
                          {this.renderInvoiceEditingArea()}
                          {[
                            "MCD1018",
                            "MCD1024",
                            "MCD1214",
                            "MCD1221",
                            "MCD1229",
                            "MCD1053",
                          ].includes(expenseType.code) && (
                            <TravelShare
                              amount={amount}
                              currencyCode={nowCurrency.currencyCode}
                              currencyList={currencyList}
                              userName={
                                (this.props.expenseReport || {})
                                  .applicantName ||
                                (nowExpense.owner &&
                                  nowExpense.owner.fullName) ||
                                this.props.agentName ||
                                this.props.user.fullName
                              }
                              userOID={userOID}
                              onChange={this.changeShareData}
                              nowExpense={nowExpense}
                              feeAcknowledgers={this.state.feeAcknowledgers}
                              onChangeSwitch={this.changeSwitch}
                              readOnly={readOnly && !thirdEditField}
                            />
                          )}
                          {!this.props.readOnly &&
                            showBusinessCardBtn &&
                            !isDiDiChange &&
                            (type === 3
                              ? (isOfficialCard && isOfficialCard !== "0") ||
                                isOfficialCard === 1
                              : true) && (
                              <FormItem
                                {...formItemLayout}
                                label={
                                  type === 2
                                    ? "消费账单"
                                    : messages(
                                        "mcd.myAccount.publicServiceCardBankBill.linkOfficialCard"
                                      ) /* 关联公务卡 */
                                }
                              >
                                <div
                                  style={{
                                    color: "#77A9F9",
                                    cursor: "pointer",
                                  }}
                                  onClick={() =>
                                    this.setState({
                                      nowPage: "card",
                                      typeSource: "businessCard",
                                      fromExpense: true,
                                      isBusinessCardMore: false,
                                    })
                                  }
                                >
                                  <Icon type="plus" />
                                  关联公务卡消费记录
                                  <div
                                    style={{
                                      color: "#4E5B71",
                                      fontSize: "12px",
                                      height: "12px",
                                      lineHeight: "12px",
                                    }}
                                  >
                                    (已选中&nbsp;
                                    <span style={{ fontWeight: "bold" }}>
                                      {checkedNum}
                                    </span>
                                    &nbsp; 笔消费记录，合计&nbsp;
                                    <span style={{ fontWeight: "bold" }}>
                                      {oriCurCod}&nbsp;
                                      {this.addCommas(recordOriAmount)}
                                    </span>
                                    <span>/</span>
                                    <span style={{ fontWeight: "bold" }}>
                                      {nowCurrency.currency}&nbsp;
                                      {this.addCommas(businessCardTotalAmount)}
                                    </span>
                                    )
                                  </div>
                                </div>
                              </FormItem>
                            )}

                          {!this.props.readOnly &&
                            isDiDiChange &&
                            !this.props.isDiDi && (
                              <FormItem {...formItemLayout} label={"消费账单"}>
                                <div
                                  style={{
                                    color: "#77A9F9",
                                    cursor: "pointer",
                                  }}
                                  onClick={() =>
                                    this.setState({
                                      typeSource: "didiCard",
                                      nowPage: "card",
                                    })
                                  }
                                >
                                  <Icon type={isRelationDidi? "swap" : 'plus'} />&nbsp;&nbsp;
                                  {isRelationDidi
                                      ?   "重新关联滴滴消费记录"
                                      :  "关联滴滴费用"}
                                  <div
                                    style={{
                                      color: "#4E5B71",
                                      fontSize: "12px",
                                      height: "12px",
                                      lineHeight: "12px",
                                    }}
                                  >
                                    (
                                    {isRelationDidi
                                      ? "已关联滴滴费用"
                                      : "请关联滴滴费用"}
                                    &nbsp;
                                    <span style={{ fontWeight: "bold" }}>
                                      总金额 CNY&nbsp;
                                      {this.addCommas(
                                        this.state.didiRelationAmount
                                      )}
                                    </span>
                                    )
                                  </div>
                                </div>
                              </FormItem>
                            )}

                          {expenseType.fields
                            ? expenseType.fields.map((field) => {
                              // console.log('field>>>>>>', field);
                              

                                let formItemVisible = true;
                                const messageKeys = [
                                  "arrive.time",
                                  "depart.time",
                                  "depart.place",
                                  "destination",
                                  "destination.original",
                                  "depart.place.original",
                                ];
                                const unitPriceModeFlag =
                                  !nowExpense.mileageAllowanceExpenseV2DTO ||
                                  (nowExpense.mileageAllowanceExpenseV2DTO &&
                                    nowExpense.mileageAllowanceExpenseV2DTO
                                      .carOrderMode === 9001); // 9001 单价 9002 阶梯
                                if (
                                  field.messageKey === "company.payment.type"
                                ) {
                                  //fix bug 28777
                                  let tempKey;
                                  expenseType.fields.map((fieldItem) => {
                                    if (
                                      fieldItem.fieldType === "COMPANY_PAID"
                                    ) {
                                      tempKey = fieldItem.fieldOID;
                                    }
                                  });
                                  formItemVisible =
                                    tempKey && getFieldValue(tempKey);
                                }

                                if (
                                  field.messageKey === "associate.application"
                                ) {
                                  const value = this.state
                                    .showAssociateApplication;
                                  if (typeof value === "boolean") {
                                    formItemVisible = value;
                                  }
                                }

                                if (
                                  messageKeys.indexOf(field.messageKey) > -1 &&
                                  field.messageKey !== "destination.original" &&
                                  field.messageKey !== "depart.place.original"
                                ) {
                                  nowExpense.mileageAllowanceExpenseV2DTO &&
                                    (field.editable =
                                      nowExpense.mileageAllowanceExpenseV2DTO.editable);
                                }
                                let label = field.name;
                                if (
                                  field.fieldTips &&
                                  field.fieldTips.length > 0
                                ) {
                                  label = (
                                    <span>
                                      {label}&nbsp;
                                      <Tooltip title={field.fieldTips}>
                                        <Icon type="question-circle-o" />
                                      </Tooltip>
                                    </span>
                                  );
                                }
                                // 当入住人数为2是前端限制同住人字段必填 后拓展为其他字段也用该变量判断
                                let togetherFlag = false;
                                if(field.messageKey === 'participant'){
                                  let togetherNum;
                                  let fieldOID;
                                  expenseType.fields.forEach(item=>{
                                    if(item.messageKey === 'ruzhu'){
                                      fieldOID = item.fieldOID;
                                    }
                                  })
                                  let getValue = fieldOID && this.props.form.getFieldValue(fieldOID);    
                                  if(getValue && getValue.length){
                                    togetherNum = getValue[0].value;
                                  }
                                  if(togetherNum === '002'){
                                    togetherFlag = true;
                                  }
                                }
                                // 通过公务卡生成费用时隐藏三个字段
                                if(type === 1){
                                  if(field.name === '无法提供电子支付凭证申请单' || ['dianzizhif', 'wudianzizhif'].includes(field.messageKey)){
                                    field.showOnList = false;
                                  }
                                }
                                if(field.name === '无法提供电子支付凭证申请单'){
                                  console.log('无法提供电子支付凭证申请--');
                                  togetherFlag = this.isRequiredApply(expenseType)
                                }
                                
                                return (
                                  formItemVisible &&
                                  field.showOnList &&
                                  ((unitPriceModeFlag &&
                                    !~mileageMessageKey.indexOf(
                                      field.messageKey
                                    )) ||
                                    (!unitPriceModeFlag &&
                                      !~messageKeys.indexOf(
                                        field.messageKey
                                      ))) && (
                                    <section>
                                      {field.messageKey === "depart.time" &&
                                        nowExpense.mileageAllowanceExpenseV2DTO && (
                                          <FormItem
                                            label={
                                              messages(
                                                "my-account.key332"
                                              ) /*行程图*/
                                            }
                                            {...formItemLayout}
                                          >
                                            <WayPointMap
                                              record={
                                                nowExpense
                                                  .mileageAllowanceExpenseV2DTO
                                                  .mileageAllowanceOrders[0]
                                              }
                                            />
                                          </FormItem>
                                        )}
                                      {(field.name == "参与人清单" ||
                                        field.name == "接收人清单") &&
                                      !this.state.isShowPlayerList ? (
                                        ""
                                      ) : (
                                        <FormItem
                                          {...formItemLayout}
                                          label={label}
                                          key={`${field.fieldOID}`}
                                        >
                                          {getFieldDecorator(
                                            `${field.fieldOID}`,
                                            {
                                              rules: [
                                                {
                                                  // required: field.required,
                                                  // 括号里的逻辑是原来的 没动
                                                  required: togetherFlag ? true : ([
                                                    "associate.application",
                                                    "public.assembly",
                                                  ].includes(field.messageKey)
                                                    ? field.isHidden
                                                      ? field.isSwitchOn
                                                        ? field.name ===
                                                            "接收人情况是否与申请单不同" ||
                                                          field.name ===
                                                            "参与人情况是否与申请单不同"
                                                          ? false
                                                          : field.required
                                                        : false
                                                      : field.required
                                                    : field.required),
                                                  message:
                                                    field.name ===
                                                    "未通过TMC购买国内机票申请"
                                                      ? "请关联未通过TMC购买国内机票申请"
                                                      : messages(
                                                          "common.name.is.required",
                                                          { name: field.name }
                                                        ),
                                                },
                                                ...this.getFieldRules(
                                                  field,
                                                  expenseType.fields
                                                ),
                                              ],
                                              valuePropName: ~[
                                                "COMPANY_PAID",
                                                "BOOLEAN",
                                              ].indexOf(field.fieldType)
                                                ? "checked"
                                                : "value",
                                              initialValue: this.getFieldDefaultValue(
                                                field.fieldType,
                                                field.value ||
                                                  field.defaultValueKey,
                                                field.showValue,
                                                field
                                              ),
                                            }
                                          )(
                                            this.switchField(
                                              field,
                                              isSubsidyType,
                                              isMile
                                            )
                                          )}
                                        </FormItem>
                                      )}
                                      {field.messageKey ===
                                        "depart.place.original" &&
                                        nowExpense.mileageAllowanceExpenseV2DTO && (
                                          <FormItem
                                            label={
                                              messages(
                                                "my-account.key326"
                                              ) /*途径信息*/
                                            }
                                            {...formItemLayout}
                                          >
                                            {getFieldDecorator("viaPoints", {
                                              rules: [
                                                {
                                                  validator: this
                                                    .handleViaPointsValidator,
                                                },
                                              ],
                                              initialValue:
                                                nowExpense
                                                  .mileageAllowanceExpenseV2DTO
                                                  .mileageAllowanceOrders[0]
                                                  .viaPoints,
                                            })(
                                              <WayPointEdit
                                                disabled={
                                                  !nowExpense
                                                    .mileageAllowanceExpenseV2DTO
                                                    .editable
                                                }
                                                onchange={this.handleViaPoints}
                                              />
                                            )}
                                          </FormItem>
                                        )}
                                    </section>
                                  )
                                );
                              })
                            : null}
                          {hasExpenseApportion &&
                            isWorthAmount &&
                            nowCurrency.currencyCode && (
                              <ExpenseApportion
                                value={expenseApportion}
                                amount={amount}
                                taxRate={taxRate}
                                apportionEnable={apportionEnable}
                                currencyCode={nowCurrency.currencyCode}
                                actualApportionAmount={actualApportionAmount}
                                readOnly={readOnly}
                                expenseReportOID={
                                  expenseReport.expenseReportOID
                                }
                                formOID={expenseReport.formOID}
                                invoiceOID={nowExpense.invoiceOID}
                                expenseTypeId={expenseType.id}
                                ownerOID={userOID}
                                costCenterItemsApportion={
                                  costCenterItemsApportion
                                }
                                expenseReport={expenseReport}
                                receiptList={receiptList || []}
                                onChange={this.handleChangeExpenseApportion}
                                jobInfo={jobInfo}
                                expenseTypeCode={expenseType.code}
                                costAttribute={expenseType.costAttribute}
                                expenseTypeOid={expenseType.expenseTypeOID}
                                createdDate={nowExpense.createdDate}
                                nowDate={this.state.nowDate}
                                modeType={
                                  this.props.nowExpense && !this.props.isCopy
                                }
                                expenseTypeName={expenseType.name}
                              />
                            )}
                          {expenseType.code === "MCD1027" ||
                          expenseType.code === "MCD1410" ? (
                            <FormItem
                              {...formItemLayout}
                              label="私车公用使用费用报告"
                            >
                              {/*<a href="https://tes-static-1256351955.cos.ap-shanghai.myqcloud.com/208e5756-cb85-444c-b6ef-02624fea15c6/other/a4626b3e-be39-4c15-8599-7d1d876826a0-%E9%99%84%E4%BB%B6H2-%E7%A7%81%E8%BD%A6%E5%85%AC%E5%8A%A1%E4%BD%BF%E7%94%A8%E8%B4%B9%E7%94%A8%E6%8A%A5%E5%91%8A.xlsx" download="私车公用使用费用报告">私车公用使用费用报告</a>*/}
                              <a
                                href="https://tes-static-1256351955.cos.ap-shanghai.myqcloud.com/208e5756-cb85-444c-b6ef-02624fea15c6/other/c14a97fa-7cc4-406a-952a-7d5c810b1c23-%E9%99%84%E4%BB%B6H1-%E7%A7%81%E8%BD%A6%E5%85%AC%E5%8A%A1%E4%BD%BF%E7%94%A8%E8%B4%B9%E7%94%A8%E6%8A%A5%E5%91%8A.xlsx"
                                download="私车公用使用费用报告"
                              >
                                私车公用使用费用报告
                              </a>
                            </FormItem>
                          ) : (
                            ""
                          )}
                          {!isMile && (
                            <FormItem
                              {...formItemLayout}
                              label={
                                expenseType.fisTipsShow
                                  ? this.renderTips(
                                      messages("common.attachments"),
                                      expenseType.ffieldTips
                                    )
                                  : messages("common.attachments") /*附件*/
                              }
                              style={{ marginBottom: 12 }}
                              required={this.isRequiredFile()}
                            >
                              <Condition>
                                <If value={window.ISIE9}>
                                  <IeFileUpload
                                    defaultFileList={attachments}
                                    attachmentType="INVOICE_IMAGES"
                                    fileSize={10}
                                    maxNum={9}
                                    showMaxNum
                                    isShowDefault
                                    token={this.props.authToken.access_token}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    disabled={isMile && !lovEditable}
                                    onChange={this.uploadSuccess}
                                  />
                                </If>
                                <Else>
                                  <FileUpload
                                    defaultFileList={attachments}
                                    attachmentType="INVOICE_IMAGES"
                                    onChange={this.uploadSuccess}
                                    isShowDefault
                                    maxNum={9}
                                    showMaxNum
                                    fileSize={10}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    disabled={isMile && !lovEditable}
                                  />
                                </Else>
                              </Condition>
                            </FormItem>
                          )}
                          {/* 3、账本：如关联公务卡，无需必填，费用保存时校验，强管控 */}
                          {/* 配置了类型并且没关联公务卡 才展示 */}
                          {!notShowFileList.includes(expenseType.code) && businessCardConsumptions.length === 0 && type !== 1 &&  (
                            <FormItem
                              {...formItemLayout}
                              label={messages("common.attachments.electronic.payment") /*电子支付凭证*/}
                              style={{ marginBottom: 12 }}
                              required={this.isRequiredNewFile(expenseType)}

                            >
                              <Condition>
                                <If value={window.ISIE9}>
                                  <IeFileUpload
                                    multiple
                                    defaultFileList={electronicAttachments}
                                    attachmentType="INVOICE_IMAGES"
                                    fileSize={10}
                                    maxNum={99}
                                    showMaxNum
                                    isShowDefault
                                    token={this.props.authToken.access_token}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    disabled={isMile && !lovEditable}
                                    // handleDelete={this.deleteElectronicAttachment}
                                    onChange={this.uploadElectronicSuccess}
                                  />
                                </If>
                                <Else>
                                  <FileUpload
                                    multiple
                                    defaultFileList={electronicAttachments}
                                    attachmentType="INVOICE_IMAGES"
                                    // handleDelete={this.deleteElectronicAttachment}
                                    onChange={this.uploadElectronicSuccess}
                                    isShowDefault
                                    maxNum={99}
                                    showMaxNum
                                    fileSize={10}
                                    placeHolder={messages(
                                      "components.key655",
                                      {
                                        arg1: 10,
                                      } /*支持格式：JPG/PNG/PPT/PDF/EXCEL/WORD/TXT/MSG，单个小于{arg1}M*/
                                    )}
                                    disabled={isMile && !lovEditable}
                                  />
                                </Else>
                              </Condition>
                            </FormItem>
                          )}
                          <FormItem
                            {...formItemLayout}
                            label={
                              expenseType.pisTipsShow
                                ? this.renderTips(
                                    messages("common.subjectmatter"),
                                    expenseType.pfieldTips
                                  )
                                : messages("common.subjectmatter" /*事由说明*/)
                            }
                          >
                            {getFieldDecorator("comment", {
                              initialValue: "",
                              rules: [
                                {
                                  required: expenseType.titleRequired,
                                  message: `${messages("common.please.enter")}`,
                                  whitespace: true,
                                },
                              ],
                            })(
                              <TextArea
                                rows={4}
                                style={{ width: "100%" }}
                                onChange={this.onRemarkChange}
                                maxLength="200"
                                disabled={isMile && !lovEditable}
                                placeholder={
                                  expenseType.titlePlaceholder ||
                                  `${messages(
                                    "common.please.enter"
                                  )}, ${messages(
                                    "common.max.characters.length",
                                    { max: 200 }
                                  )}`
                                }
                              />
                            )}
                          </FormItem>

                                {
                                // this.props.params.didiExpenseInfo.length > 0 ?
                                didiCardArr.sort((i,j)=> moment(i.departureTime).diff(moment(j.departureTime),'days')).map(record => {
                                  console.log(record,'交易金额')
                                    return (
                                      <div>
                                    <div className="title">{"滴滴消费明细"}</div>
                                  <div
                                    className="detailsContainer"
                                    style={{ padding: "0px", marginLeft: "1px" }}
                                  >
                                     <div className={"detailBlock"}>
                                              <div
                                                style={{ fontSize: "12px" }}
                                                className={"detailHead"}
                                              >
                                                <div className="didiDetails">
                                                  <span className={"headText"}>交易金额：</span>
                                                  <span className={'headText'}>{'CNY'}</span>
                                                  <span className={'headText'}>{this.addCommas(Number(record.companyRealPay || '0').toFixed(2))}</span>
                                                </div>
                                                <div className="didiDetails">
                                                  <span className={"headText"}>交易日期：</span>
                                                  <span className={"headText"}>
                                                    {record.payTime
                                                      ? moment(record.payTime).format("YYYY-MM-DD")
                                                      : "-"}
                                                  </span>
                                                </div>
                                                <div className="didiDetails">
                                                  <span className={"headText"}>上车时间：</span>
                                                  <span className={"headText"}>
                                                    {record.departureTime
                                                      ? moment(record.departureTime).format(
                                                        "YYYY-MM-DD HH:mm:ss"
                                                      )
                                                      : "-"}
                                                  </span>
                                                  <span
                                                    style={{ marginRight: "5px", marginLeft: "5px" }}
                                                  >
                                                    |
                                                  </span>
                                                  <span className={"headText"}>下车时间：</span>
                                                  <span className={"headText"}>
                                                    {record.finishTime
                                                      ? moment(record.finishTime).format("YYYY-MM-DD HH:mm:ss")
                                                      : "-"}
                                                  </span>
                                                </div>
                                                <div className="didiDetails">
                                                  <span className={"headText"}>上车地点：</span>
                                                  <span className={"headText"}>
                                                    {record.actualStartName}
                                                  </span>
                                                </div>
                                                <div className="didiDetails">
                                                  <span className={"headText"}>下车地点：</span>
                                                  <span className={"headText"}>
                                                    {record.actualEndName}
                                                  </span>
                                                </div>
                                              </div>
                                            </div>
                                  </div>
                                  </div>
                                    )

                                  })
                                  // :null
                                }


                        </div>
                      )}
                      {/* 里程字段 */}
                      {mileageAllowanceExpenseDTO && (
                        <MileageAllowance
                          mileageAllowance={mileageAllowanceExpenseDTO}
                          currencyPrecision={invoiceCurrencyCodePrecision}
                        />
                      )}
                    </div>
                  </Spin>
                  {nowExpense.expenseTypeSubsidyType === 1 &&
                    subsidyData.length > 0 && (
                      <div>
                        {" "}
                        {messages("my-account.key118" /*补贴明细*/)}:
                        <Table
                          dataSource={subsidyData}
                          columns={columns}
                          loading={subsidyLoading}
                          bordered
                          className="expense-subsidy-table"
                          size="middle"
                          rowClassName={(record) =>
                            record.repeatedFlag ? "repeat-subsidy-item" : ""
                          }
                          pagination={pagination}
                        />
                      </div>
                    )}
                  <ApproveHistory approvalHistory={approvalHistory || []} />
                </Form>

                {/** 公务卡消费明细 */}


              </div>
            </Col>
          </Row>
        </div>

        {/* 低部提交按钮*/}
        {nowPage === "form" && (
          <div className="footer-operate">
            {(!readOnly || thirdEditAmount || thirdEditField) && (
              <Button
                type="primary"
                disabled={rateDeviation > prohibitExchangeRateTol}
                onClick={this.handleSave}
                loading={saving}
              >
                {messages("common.save")}
              </Button>
            )}
            <Button onClick={this.onCancel}>
              {messages(
                readOnly && !thirdEditField ? "common.back" : "common.cancel"
              )}
            </Button>
            {expenseReport &&
              nowExpense.invoiceOID &&
              readOnly &&
              !thirdEditField && (
                <div className="footer-page">
                  <Button
                    type="primary"
                    ref="lastInvoiceButton"
                    disabled={typeof lastInvoiceIndex !== "number"}
                    onClick={() =>
                      typeof lastInvoiceIndex === "number"
                        ? this.setState(
                            { showExpenseDom: !showExpenseDom },
                            () => {
                              this.props.params.switchingInvoice(
                                lastInvoiceIndex
                              );
                            }
                          )
                        : message.info(
                            messages("common.no.more") /*'没有更多了'*/
                          )
                    }
                  >
                    <Icon type="left" />
                    {/*上一条*/}
                    {messages("common.last.one")}
                  </Button>
                  <Button
                    type="primary"
                    ref="nextInvoiceButton"
                    disabled={typeof nextInvoiceIndex !== "number"}
                    onClick={() =>
                      typeof nextInvoiceIndex === "number"
                        ? this.setState(
                            { showExpenseDom: !showExpenseDom },
                            () => {
                              this.props.params.switchingInvoice(
                                nextInvoiceIndex
                              );
                            }
                          )
                        : message.info(
                            messages("common.no.more") /*'没有更多了'*/
                          )
                    }
                  >
                    <Icon type="right" />
                    {/*下一条*/}
                    {messages("common.next.one")}
                  </Button>
                </div>
              )}
          </div>
        )}
        {showExpenseReportInvoices && showExpenseReportInvoices.length > 0 && (
          <FileAudit
            visible={showFileAudit}
            defaultImage={defaultAttachment}
            isEnableCheck={(audit && isWaitForAudit) || auditCapability}
            onAuditChange={(value) =>
              this.setState({ showExpenseReportInvoices: value || [] })
            }
            onCancel={() => this.setState({ showFileAudit: false })}
            invoices={this.handleAllowedFileInvoices(showExpenseReportInvoices)}
          />
        )}
        {type === 2 && (
          <Modal
            visible={this.state.showDiDiModal}
            onCancel={() => this.setState({ showDiDiModal: false })}
            onOk={() => this.handleOnCreateExpense()}
          >
            <div
              style={{
                marginRight: "16px",
                height: "24px",
                lineHeight: "24px",
                fontSize: "16px",
                fontWeight: 400,
                color: "rgba(0, 0, 0, 0.85)",
                marginBottom: "12px",
              }}
            >
              <Icon
                style={{
                  fontSize: "22px",
                  color: "#FAAD14",
                  verticalAlign: "middle",
                  marginRight: "16px",
                }}
                type="question-circle"
                theme="filled"
              />
              <span style={{ verticalAlign: "middle" }}>提示信息</span>
            </div>
            <div style={{ fontSize: "14px", marginLeft: "38px" }}>
              {this.state.didiModalInfo}
            </div>
          </Modal>
        )}
      </DivExpense>
    );
  }
}

function mapStateToProps(state) {
  console.log("this.props.user", this.props);
  return {
    company: state.login.company,
    companyConfiguration: state.login.companyConfiguration,
    profile: state.login.profile,
    user: state.login.user,
    language: state.main.language,
    authToken: state.main.authToken,
  };
}

const WrappedNewExpense = Form.create({
  onValuesChange(props, values) {
    newExpenseThis.formItemChange(values);
  },
})(NewExpense);

export default connect(mapStateToProps)(WrappedNewExpense);
